简体   繁体   English

通过反射设置静态字段是否可以保证调用类型初始化程序?

[英]Is setting a static field via reflection guaranteed to call type initializer?

The following code sets the value of a static field and the initializer (static constructor) is called. 以下代码设置静态字段的值,并调用初始化程序(静态构造函数)。

public class Foo
{
    static Foo()
    {
        Console.WriteLine("Initialized");
    }
    public static string Bar;
}

static Program()
{
    FieldInfo fld = typeof(Foo).GetField("Bar");
    fld.SetValue(null, ""); // cctor gets called
}

Will this always happen; 这会一直发生吗? does setting a static field via reflection guarantee the static constructor will run if it hasn't already? 通过反射设置静态字段是否可以确保静态构造函数(如果尚未运行)运行?

if you access any member of the class, the runtime will invoke the static constructor automatically for you. 如果您访问该类的任何成员,则运行时将自动为您调用静态构造函数。

Meaning that yes, the static constructor will run if it hasn't already, this is one of the advantages of reflection. 意思是,如果静态构造函数尚未运行,它将运行,这是反射的优点之一。

You do not have to initialize it directly, only access it's properties. 您不必直接对其进行初始化,只需访问其属性即可。 this will work as well: 这也将工作:

Type myClass = typeof(MyClass);
myClass.GetField("SomeValue").GetValue(null);

If you do want to invoke it explicitly, you can use this: 如果确实要显式调用它,则可以使用以下命令:

myClass.TypeInitializer.Invoke(null, null);

Though it is not a good practice and not recommended, I would strongly recommend that you don't do this, however - it violates a type expecting the static constructor to only be executed once . 尽管这不是一个好的做法,所以不建议这样做,但是我强烈建议您不要这样做,因为它违反了一个期望静态构造函数仅执行一次的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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