简体   繁体   中英

FieldInfo.SetValue on a Nested Static Class using Reflection

I am struggling with obtaining the "object" to be able to set a value on a nested class, and I suspect that I am going to struggle with how to manipulate it after it is set. Example follows:

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";
    }
}

The following code uses reflection to obtain the Data field, however I can not see how to obtain the "object" to pass into 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;
    }
}

Thanks.

OK, turns out that with a little more research (asking the question slightly differently in Google) and I have found the answer:

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

According to the answer here: Is it possible to set this static private member of a static class with reflection?

It states in the code section:

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

I am not going to suggest that I understand that. But the code is working! Rather than just delete this question I will post the answer here for others as I did struggle to find answer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM