Using Reflection to set a static variable value before object's initialization?

后端 未结 2 1884
天涯浪人
天涯浪人 2020-12-16 10:19

Is there anyway to set the value of a static (private) variable on an object that has not been initialized? The SetValue method requires an instance, but I\'m h

相关标签:
2条回答
  • 2020-12-16 10:34

    For static values you can pass null for the instance parameter.

    var type = typeof(SomeClass);
    var field = type.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Static);
    field.SetValue(null, 42);
    
    0 讨论(0)
  • 2020-12-16 10:34

    could you create a static function that is public and use it to set your private static variable ?

    0 讨论(0)
提交回复
热议问题