.net c#使用反射在对象初始化之前设置静态变量值?

Using Reflection to set a static variable value before object's initialization?
2021-02-23
  •  译文(汉语)
  •  原文(英语)

无论如何,是否可以在尚未初始化的对象上设置静态(私有)变量的值?该SetValue方法需要一个实例,但是我希望有一种解决方法.

解决过程1

对于静态值,您可以为实例参数传递null.

var type = typeof(SomeClass);
var field = type.GetField("SomeField", BindingFlags.NonPublic | BindingFlags.Static);
field.SetValue(null, 42);
速聊1:
+1令人着迷:我发现这种技术有点让人害怕:如果有问题的字段是只读的,则该代码在执行时不会引起运行时错误.
速聊2:
如果所讨论的字段是只读的,它什么都不做?还是设置值?这就是.NET 3.5吗?
速聊3:
+1.我认为对于私有静态,您需要一些BindingFlags作为GetField方法的第二个参数.BindingFlags.Static | BindingFlags.NonPublic
解决过程2

您能否创建一个公共的静态函数并使用它来设置您的私有静态变量?

速聊1:
我猜想这与@Chance没有源代码的类型相反.
速聊2:
是的,我无法理解源代码,而且很遗憾,我无法使用2.0扩展方法.不过谢谢!
速聊3:
扩展方法无法访问私有数据. msdn.microsoft.com/zh-CN/library/bb383977.aspx

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.

Solutions1

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);
Talk1:
+1 fascinating : what I find a little scary in this technique is : if the field in question is readonly : this code will not cause a run-time error when executed.
Talk2:
If the field in question is read-only, does it just do nothing? Or does it set the value anyway? Is this just .NET 3.5?
Talk3:
+1. I think for private static you need some BindingFlags as the second parameter of the GetField method. BindingFlags.Static | BindingFlags.NonPublic
Solutions2

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

Talk1:
I'm guessing this is against a type for which @Chance does not have source code.
Talk2:
Yea, I can't muck around with the source & I'm unfortunately blocked into 2.0 w/out extension methods. Thanks though!
Talk3:
Extension methods cannot access private data. msdn.microsoft.com/en-us/library/bb383977.aspx
转载于:https://stackoverflow.com/questions/23712629/using-variable-as-a-name

本人是.net程序员,因为英语不行,使用工具翻译,希望对有需要的人有所帮助
如果本文质量不好,还请谅解,毕竟这些操作还是比较费时的,英语较好的可以看原文

留言回复
我们只提供高质量资源,素材,源码,坚持 下了就能用 原则,让客户花了钱觉得值
上班时间 : 周一至周五9:00-17:30 期待您的加入