[英]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(). 下面的代码使用反射来获取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;
}
}
Thanks. 谢谢。
OK, turns out that with a little more research (asking the question slightly differently in Google) and I have found the answer: 好的,事实证明,通过更多的研究(在Google中提出的问题稍有不同),我找到了答案:
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.
我将不仅仅删除此问题,因为我确实很难找到答案,所以我将在这里将答案发布给其他人。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.