简单案例:
public class MyClass
{
public Action<double> MyAction;
}
public class AnotherClass
{
public void MyAction(double value)
{
// ...
}
}
当我通过反射获得 AnotherClass.MyAction(..)
方法和 MyClass.MyAction
委托(delegate)时,我最终得到了一对 MethodInfo/FieldInfo 类,其中我无法将方法连接到委托(delegate)。此外,我从字符串中获取了方法/委托(delegate)名称,我无法在没有反射的情况下访问实例字段/方法。谁能帮我解决这个问题,或者这种联系是否可行?
最佳答案
您应该查看 Delegate.CreateDelegate
,特别是:
MethodInfo method = typeof(AnotherClass).GetMethod("MyAction");
FieldInfo field = typeof(MyClass).GetField("MyAction");
AnotherClass obj = // the object you want to bind to
Delegate action = Delegate.CreateDelegate(field.FieldType, obj, method);
MyClass obj2 = // the object you want to store the delegate in
field.SetValue(obj2, action);
关于c# - 将 MethodInfo 连接到委托(delegate)字段 (FieldInfo),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6436215/