C#中的类Initialize()?

时间:2014-12-15 09:45:07

标签: c#

在Obj-c中有静态Initialize方法,该方法在第一次使用该类时被调用,无论是静态还是实例。在C#中有类似的东西吗?

3 个答案:

答案 0 :(得分:3)

您可以使用与普通构造函数相同的语法编写静态构造函数,但使用static修饰符(并且没有访问修饰符)除外:

public class Foo {
    static Foo() {
        // Code here
    }
}

通常你不需要这样做,但是 - 静态构造函数用于初始化,通常只能在静态字段初始化器中执行:

public class Foo {
    private static readonly SomeType SomeField = ...;
}

如果你使用静态构造函数做的不仅仅是初始化静态字段,那么通常一种设计气味 - 但并非总是如此。

请注意,存在静态构造函数subtly affects the timing of type initialization,要求在第一次使用之前执行 - 在第一次静态成员访问时或第一次实例之前创建,以先发生者为准。

答案 1 :(得分:2)

有一个static构造函数。根据{{​​3}}:

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.

公共课Foo {     static Foo(){} //静态构造函数 }

答案 2 :(得分:-2)

是的,它被称为constructor

通过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