静态构造函数, 静态成员初始化/调用顺序
1)第一次調(diào)用類(lèi)的任何成員之前,執(zhí)行靜態(tài)成員的初始化動(dòng)作,執(zhí)行順序是:靜態(tài)成員初始化--->靜態(tài)構(gòu)造函數(shù)--->調(diào)用類(lèi)的某成員(構(gòu)造器,靜態(tài)字段/屬性/函數(shù),)
2)在創(chuàng)建第一個(gè)實(shí)例或引用任何靜態(tài)成員之前,將自動(dòng)調(diào)用靜態(tài)構(gòu)造函數(shù)。調(diào)用靜態(tài)構(gòu)造函數(shù)之前會(huì)先做靜態(tài)成員的初始化。同1)。
如果類(lèi)包含靜態(tài)字段,請(qǐng)?zhí)峁┰诩虞d類(lèi)時(shí)初始化這些字段的靜態(tài)構(gòu)造函數(shù)。在應(yīng)用程序域的生存期內(nèi),靜態(tài)類(lèi)一直保留在內(nèi)存中。
總結(jié):創(chuàng)建實(shí)例,引用/調(diào)用靜態(tài)字段/函數(shù)會(huì)導(dǎo)致CLR 初始化靜態(tài)成員和調(diào)用靜態(tài)構(gòu)造函數(shù)。只是獲取type類(lèi)型或者沒(méi)有關(guān)于類(lèi)的任何引用代碼,靜態(tài)成員的初始化和靜態(tài)構(gòu)造函數(shù)不會(huì)執(zhí)行。
示例程序,main函數(shù)中分別打開(kāi)TestCast1,2,3,4. 觀察運(yùn)行結(jié)果:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace static_const_readonly
{
class MyClass
{
public static readonly int Count = 0;
public static MyTest TEST = new MyTest();
static MyClass()
{
Console.WriteLine("static MyClass() ctor.");
TEST = new MyTest();
}
public static void FuncStatic()
{
Console.WriteLine("static void FuncStatic().");
}
public MyClass()
{
Console.WriteLine("MyClass() ctor");
}
}
class MyTest
{
public MyTest()
{
Console.WriteLine("My Test ctor.");
}
}
class Program
{
static void TestCast1()
{
Console.WriteLine("test starts.");
MyClass myobject = new MyClass(); // call ctor
}
static void TestCast2()
{
Console.WriteLine("test starts.");
Console.WriteLine("static MyClass.Count = {0}.", MyClass.Count); // get MyClass.Count
}
static void TestCast3()
{
Console.WriteLine("test starts."); // not refer to MyClass
Console.WriteLine(typeof(MyClass));
}
static void TestCast4()
{
Console.WriteLine("test starts."); // not refer to MyClass
MyClass.FuncStatic();
}
static void TestCast5()
{
Console.WriteLine("test starts."); // not refer to MyClass
}
static void Main(string[] args)
{
//TestCast1();
//TestCast2();
//TestCast3();
TestCast4();
// TestCast5();
}
}
}
TestCase1結(jié)果:
test starts.
My Test ctor.
static MyClass() ctor.
My Test ctor.
MyClass() ctor
TestCase2結(jié)果:
test starts.
My Test ctor.
static MyClass() ctor.
My Test ctor.
static MyClass.Count = 0.
TestCase3結(jié)果:
test starts.
static_const_readonly.MyClass
TestCase4結(jié)果:
test starts.
My Test ctor.
static MyClass() ctor.
My Test ctor.
static void FuncStatic().
TestCase5結(jié)果:
test starts.
總結(jié)
以上是生活随笔為你收集整理的静态构造函数, 静态成员初始化/调用顺序的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 深入理解Solidity
- 下一篇: 英语口语 week14 Friday