如何通过反射引用字段
-
30-09-2019 - |
题
抱歉,标题不明确。
进一步回答我之前的问题, ,我想订阅动态检索的事件对象的方法(通过反射)。有问题的对象是 Control 的一个字段:
public void SubscribeEvents(Control control)
{
Type controlType = control.GetType();
FieldInfo[] fields = controlType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo method = typeof(Trace).GetMethod("WriteTrace");
// "button1" hardcoded for the sample
FieldInfo f = controlType.GetField("button1", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// "Click" hardcoded for the sample
EventInfo eInfo = f.FieldType.GetEvent("Click");
if (eInfo != null)
{
EventHandler dummyDelegate = (s, e) => WriteTrace(s, e, eInfo.Name);
Delegate realDelegate = Delegate.CreateDelegate(eInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);
eInfo.AddEventHandler(?????, realDelegate); // How can I reference the variable button1 ???
}
}
我不知道如何引用变量“button1”。我尝试过这样的事情:
public void SubscribeEvents(Control control)
{
Type controlType = control.GetType();
FieldInfo[] fields = controlType.GetFields(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo method = typeof(Trace).GetMethod("WriteTrace");
// "button1" hardcoded for the sample
FieldInfo f = controlType.GetField("button1", BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
// "Click" hardcoded for the sample
EventInfo eInfo = f.FieldType.GetEvent("Click");
Type t = f.FieldType;
object o = Activator.CreateInstance(t);
f.GetValue(o);
if (eInfo != null)
{
EventHandler dummyDelegate = (s, e) => WriteTrace(s, e, eInfo.Name);
Delegate realDelegate = Delegate.CreateDelegate(eInfo.EventHandlerType, dummyDelegate.Target, dummyDelegate.Method);
eInfo.AddEventHandler(o, realDelegate); // Why can I refer to the variable button1 ???
}
}
但我这里有一个例外:
f.GetValue(o);
System.ArgumentException是未经用来的消息=字段'button1'在类型'WindowsFormsApplication1.form1'上定义的字段不是目标对象上的字段,即类型为'system.windows.windows.forms.button'的字段。
解决方案
那是因为您正在尝试创建一个新实例 Button
并试图获得其价值 button1
财产,显然不存在。
替换这个:
Type t = f.FieldType;
object o = Activator.CreateInstance(t);
f.GetValue(o);
有了这个:
object o = f.GetValue(control);
您可以使用这样的方法来获取任何对象的字段值:
public static T GetFieldValue<T>(object obj, string fieldName)
{
if (obj == null)
throw new ArgumentNullException("obj");
var field = obj.GetType().GetField(fieldName, BindingFlags.Public |
BindingFlags.NonPublic |
BindingFlags.Instance);
if (field == null)
throw new ArgumentException("fieldName", "No such field was found.");
if (!typeof(T).IsAssignableFrom(field.FieldType))
throw new InvalidOperationException("Field type and requested type are not compatible.");
return (T)field.GetValue(obj);
}
不隶属于 StackOverflow