无论如何,是否可以在尚未初始化的对象上设置静态(私有)变量的值?该SetValue
方法需要一个实例,但是我希望有一种解决方法.
对于静态值,您可以为实例参数传递null.
var type = typeof(SomeClass);
var field = type.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue(null, 42);
您能否创建一个公共的静态函数并使用它来设置您的私有静态变量?
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 hoping there's a way to get around this.
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);
could you create a static function that is public and use it to set your private static variable ?
本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文