对不起标题,它不明确。
Further to my precedent question,我想订阅一个方法来动态检索一个事件对象(通过反射)。有问题的对象是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未处理 Message =在'WindowsFormsApplication1.Form1'类型上定义的字段'button1'不是目标对象上的字段,类型为'System.Windows.Forms.Button'。
答案 0 :(得分:5)
那是因为您正在尝试创建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);
}