根据MSDN:
BeforeFieldInit指定调用该类型的静态方法不会强制执行 系统初始化类型。
除此之外(恕我直言),静态ctor的存在将禁用BeforeFieldInit
。
现在我想检查类型是否未初始化,如果我调用静态方法,而我的类没有静态ctor,如下所示。
using System;
namespace Static
{
class Foo
{
public Foo(string arg)
{
Console.WriteLine("Foo's ctor called by {0}.", arg);
}
}
class Goo
{
Foo f2 = new Foo("Goo's instance field.");
//static Goo()
//{
// Console.WriteLine("Goo's static ctor.");
//}
static Foo f = new Foo("Goo's static field.");
public Goo()
{
Console.WriteLine("Goo's default ctor.");
}
public static void Display()
{
Console.WriteLine("Goo's static method.");
}
}
class Program
{
static void Main(string[] args)
{
Goo.Display();
Console.ReadKey();
}
}
}
输出如下,
Foo's ctor called by Goo's static field..
Goo's static method.
为什么在调用静态方法时静态字段仍会被初始化?它似乎与MSDN上面说的不一致。
答案 0 :(得分:0)