c# - 将 MethodInfo 连接到委托(delegate)字段 (FieldInfo)

标签 c# reflection delegates

简单案例:

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/

相关文章:

iphone - CustomTabBarController 不响应委托(delegate)回调

c# - 表单可以判断是否有打开的模态窗口吗?

c# - 返回文件名

c# - 在 .NETMF 4.0 中解析 RFC822-Datetime

java - 使用对象类型作为方法的输入

vb.net - 委托(delegate)和地址

c# - 系统.InvalidCastException : Unable to cast object of type x to type y

java - Java 反射 getMethod 有时不起作用的原因是什么?

powershell - Powershell/.net反射-GetMethod()查找常规方法,但找不到通用方法-为什么?

c# - 将具有两个参数的委托(delegate)作为参数函数传递