使用Reflection的嵌套静态类上的FieldInfo.SetValue

时间:2014-02-06 03:00:03

标签: c# reflection

我正在努力获取能够在嵌套类上设置值的“对象”,并且我怀疑在设置之后我将如何操纵它。示例如下:

public class RegistryData {
    public RegistryKey rk;
}

public static class RegistryKeys {
    public static class Username {
        public static RegistryData Data = null;
        public static string DefaultValue = "MyUsername";
    }
    public static class Password {
        public static RegistryData Data = null;
        public static string DefaultValue = "MyPassword";
    }
}

以下代码使用反射来获取数据字段,但我无法看到如何获取传递给FieldInfo.SetValue()的“对象”。

static void DoReflection()
{
    Type type = typeof(RegistryKeys);
    Type[] nestedTypeArray = type.GetNestedTypes(BindingFlags.Public | BindingFlags.Static);
    foreach(Type t in nestedTypeArray)
    {
        FieldInfo field = t.GetField("Data"); // Obtain the Data field            

        // Issue 1: how to allocate the Data Field within the nested class
        field.SetValue( ??? object ??? , new RegistryData());  <---

        // Issue 2: how to access the new class within the nested class
        field.GetValue( ??? what ??? ).rk = Registry.LocalMachine;
    }
}

感谢。

1 个答案:

答案 0 :(得分:0)

好的,事实证明,通过更多的研究(在Google中提问的方式略有不同),我找到了答案:

field.SetValue( null , new RegistryData());
((RegistryData)(field.GetValue(null))).rk = Registry.LocalMachine;

根据答案:Is it possible to set this static private member of a static class with reflection?

它在代码部分中说明:

// Normally the first argument to "SetValue" is the instance
// of the type but since we are mutating a static field we pass "null"

我不打算建议我明白这一点。但代码正在运行!我不会只是删除这个问题,而是在这里为其他人发布答案,因为我很难找到答案。