2014-02-06 48 views
0

我很努力地獲得能夠在嵌套類上設置值的「對象」,並且我懷疑我會在處理它之後如何處理它已設置。例子如下:使用反射嵌套靜態類的FieldInfo.SetValue

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

謝謝。

回答

0

OK,原來,多一點研究(問這個問題在谷歌略有不同),我已經找到了答案:

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" 

我不會建議我明白這一點。但代碼正在工作!我不會只是刪除這個問題,我會在這裏爲其他人發佈答案,因爲我很難找到答案。