Flo*_*ian 2 .net reflection fieldinfo c#-2.0
对不起标题,它不明确.
继我的先例问题之后,我想订阅一个方法来动态检索一个事件对象(通过反射).有问题的对象是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 ???
}
}
Run Code Online (Sandbox Code Playgroud)
我不知道如何引用变量'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 ???
}
}
Run Code Online (Sandbox Code Playgroud)
但我有一个例外:
f.GetValue(o);
Run Code Online (Sandbox Code Playgroud)
System.ArgumentException未处理Message = Field在类型'WindowsFormsApplication1.Form1'上定义的'button1'不是目标对象上的字段,类型为'System.Windows.Forms.Button'.
那是因为你正在尝试创建一个新的实例Button
并试图获取其button1
属性的值,这显然不存在.
替换这个:
Type t = f.FieldType;
object o = Activator.CreateInstance(t);
f.GetValue(o);
Run Code Online (Sandbox Code Playgroud)
有了这个:
object o = f.GetValue(control);
Run Code Online (Sandbox Code Playgroud)
您可以使用这样的方法来获取任何对象的字段值:
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);
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5588 次 |
最近记录: |