简体   繁体   中英

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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