[英]Class Initialize() in C#?
In Obj-c there is the static Initialize
method which is called the first time that class is used, be it statically or by an instance. 在Obj-c中,有一个静态的
Initialize
方法,该方法是在第一次使用该类时被静态或实例化的。 Anything like that in C#? C#中有类似的东西吗?
You can write a static constructor with the same syntax as a normal constructor, except with the static
modifier (and no access modifiers): 您可以使用与普通构造函数相同的语法编写一个静态构造函数,但带有
static
修饰符(并且没有访问修饰符):
public class Foo {
static Foo() {
// Code here
}
}
Usually you don't need to do this, however - static constructors are there for initialization, which is normally fine to do just in static field initializers: 通常,您不需要这样做,但是-静态构造函数可用于初始化, 通常只在静态字段初始化程序中即可:
public class Foo {
private static readonly SomeType SomeField = ...;
}
If you're using a static constructor to do more than initialize static fields, that's usually a design smell - but not always. 如果您使用静态构造函数完成的工作不只是初始化静态字段,那通常是设计上的味道-但并非总是如此。
Note that the presence of a static constructor subtly affects the timing of type initialization , requiring it to be executed just prior to the first use - either when the first static member access, or before the first instance is created, whichever happens first. 请注意,一个静态构造的存在巧妙地影响类型初始化的定时 ,需要将被执行之前 ,为了在第一次使用-无论是当第一静态成员访问,或者在创建第一个实例之前,先发生者为准。
There is a static
constructor. 有一个
static
构造函数。 As per msdn : 根据msdn :
A static constructor is used to initialize any static data, or to perform a particular action that needs to be performed once only. It is called automatically before the first instance is created or any static members are referenced.
public class Foo { static Foo() {} //static constructor } 公共类Foo {static Foo(){} //静态构造函数}
Yes, it is called a constructor . 是的,它称为构造函数 。
By MSDN: 通过MSDN:
public class Taxi
{
public bool isInitialized;
//This is the normal constructor, which is invoked upon creation.
public Taxi()
{
//All the code in here will be called whenever a new class
//is created.
isInitialized = true;
}
//This is the static constructor, which is invoked before initializing any Taxi class
static Taxi()
{
Console.WriteLine("Invoked static constructor");
}
}
class TestTaxi
{
static void Main()
{
Taxi t = new Taxi(); //Create a new Taxi, therefore call the normal constructor
Console.WriteLine(t.isInitialized);
}
}
//Output:
//Invoked static constructor
//true
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.