繁体   English   中英

C#中的类Initialize()?

[英]Class Initialize() in C#?

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

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

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

通常,您不需要这样做,但是-静态构造函数可用于初始化, 通常只在静态字段初始化程序中即可:

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

如果您使用静态构造函数完成的工作不只是初始化静态字段,那通常是设计上的味道-但并非总是如此。

请注意,一个静态构造的存在巧妙地影响类型初始化的定时 ,需要将被执行之前 ,为了在第一次使用-无论是当第一静态成员访问,或者在创建第一个实例之前,先发生者为准。

有一个static构造函数。 根据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.

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

是的,它称为构造函数

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

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