Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
75 views
in Technique[技术] by (71.8m points)

c# - Is the Main Function of a Class Called When an Object of That Class is Created?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

No. The code that runs automatically when you create a class is in the constructor, which is a method that has a name the same as the class (and no return type)

public class MyClass{
  public MyClass(){
    //this is the constructor. Code here is run automatically when you make a new MyClass
  }
}

Applications typically have a Main() somewhere, and it is called automatically when the app starts, but that is the only time it is called automatically and only one of the classes in the program has a main that is called automatically.

In other words, you can have as many classes (each with Main methods) as you like but you'll have to call them manually from your code if you want them to run

class Program{
  static void Main(string[] args){
    //this method will be called automatically to kick start your code running if..
    //it is configured in the project properties that Program shall be the startup object
  }
}
class MyClass{
  static void Main(string[] args){
    //this is also a method called main, but this one won't be called automatically, ever, 
    //if the project's Startup Object is set to Program
  }
}

If you have multiple classes with a Main you can choose which one will be called upon startup, in the project settings:

enter image description here

But from there on after if you have another class with a Main you have to call it yourself


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...