[英]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.