簡體   English   中英

使用反射的嵌套靜態類上的FieldInfo.SetValue

[英]FieldInfo.SetValue on a Nested Static Class using 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";
    }
}

下面的代碼使用反射來獲取Data字段,但是我看不到如何獲取傳遞給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;
    }
}

謝謝。

好的,事實證明,通過更多的研究(在Google中提出的問題稍有不同),我找到了答案:

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

根據此處的答案: 是否可以通過反射設置靜態類的此靜態私有成員?

它在代碼部分中指出:

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

我不會建議我理解這一點。 但是代碼正在工作! 我將不僅僅刪除此問題,因為我確實很難找到答案,所以我將在這里將答案發布給其他人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM