是否可以使用reflection设置静态类的静态私有成员?
我有一个带有static private readonly
成员的static class
,它通过类的static constructor
。 下面是一个简化的例子。
public static class MyClass { private static readonly string m_myField; static MyClass() { // logic to determine and set m_myField; } public static string MyField { get { // More logic to validate m_myField and then return it. } } }
由于上面的类是一个静态类,我无法创建它的实例,以便将这样的传递用于FieldInfo.GetValue()
调用以检索并稍后设置m_myField
的值。 有没有一种方法我不知道要么使用FieldInfo类来获取和设置静态类的值,还是唯一的选择是重构我被要求进行unit testing的类?
这是一个快速示例,说明如何执行此操作:
using System; using System.Reflection; class Example { static void Main() { var field = typeof(Foo).GetField("bar", BindingFlags.Static | BindingFlags.NonPublic); // Normally the first argument to "SetValue" is the instance // of the type but since we are mutating a static field we pass "null" field.SetValue(null, "baz"); } } static class Foo { static readonly String bar = "bar"; }
这个“空规则”也适用于静态字段的FieldInfo.GetValue(),例如,
Console.Writeline((string)(field.GetValue(null)));