简体   繁体   English

C# 实例构造函数与静态构造函数

[英]C# Instance Constructor vs Static Constructor

What are the differences between the two?两者之间有什么区别? I've only used one kind of constructor and I believe it's the static constructor.我只使用了一种构造函数,我相信它是静态构造函数。 Only familiar with C++ and Java.只熟悉 C++ 和 Java。

Static constructor is called the first time your class is referenced ie第一次引用您的类时调用静态构造函数,即

MyClass.SomeStaticMethod()

Instance constructor is called every time you do ' MyClass dummy = new MyClass() ' ie create instance of the class每次执行“ MyClass dummy = new MyClass() ”时都会调用实例构造函数,即创建类的实例

Semantically first is used when you want to ensure that some static state is initialized before it is accessed, the other is used to initialize instance members.当您要确保在访问某些静态状态之前对其进行初始化时,首先使用语义,另一个用于初始化实例成员。

Static constructors allow you to initialize static variables in a class, or do other things needed to do in a class after it's first referenced in your code.静态构造函数允许您在类中初始化静态变量,或者在代码中首次引用类后执行其他需要在类中执行的操作。 They are called only once each time your program runs.每次程序运行时它们只被调用一次。

Static constructors are declared with this syntax, and can't be overloaded or have any parameters because they run when your class is referenced by its name:静态构造函数使用此语法声明,并且不能重载或具有任何参数,因为它们在您的类被其名称引用时运行:

static MyClass()
{
}

Instance constructors are the ones that are called whenever you create new objects (instances of classes).实例构造函数是在您创建新对象(类的实例)时调用的构造函数。 They're also the ones you normally use in Java and most other object-oriented languages.它们也是您通常在 Java 和大多数其他面向对象语言中使用的那些。

You use these to give your new objects their initial state.您可以使用这些来为您的新对象赋予初始状态。 These can be overloaded, and can take parameters:这些可以重载,并且可以带参数:

public MyClass(int someNumber) : this(someNumber, 0) {}

public MyClass(int someNumber, int someOtherNumber)
{
    this.someNumber = someNumber;
    this.someOtherNumber = someOtherNumber;
}

Calling code:调用代码:

MyClass myObject = new MyClass(100, 5);

The static constructor runs only once for all instances or uses of the class.对于类的所有实例或使用,静态构造函数只运行一次。 It will run the first time you use the class.它将在您第一次使用该类时运行。 Normal constructors run when you instantiate an object of the class.当您实例化类的对象时,普通构造函数会运行。

Everything you should need to know about static constructors can be found here: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors关于静态构造函数你需要知道的一切都可以在这里找到: https : //docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM