![](/img/trans.png)
[英]C# Reflection: What is the difference between FieldInfo.SetValue() and FieldInfo.SetValueDirect()?
[英]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.