Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/269.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何将事件与反射关联起来_C#_Reflection - Fatal编程技术网

C# 如何将事件与反射关联起来

C# 如何将事件与反射关联起来,c#,reflection,C#,Reflection,见下面的示例。我需要将通过对事件的反射获得的剂量测量方法连接起来 class Program { private static event EventHandler MyEvent; static void Main(string[] args) { object aType = new SomeType(); var type = aType.GetType(); var method = type.GetM

见下面的示例。我需要将通过对事件的反射获得的剂量测量方法连接起来

    class Program {
    private static event EventHandler MyEvent;

    static void Main(string[] args)
    {
        object aType = new SomeType();

        var type = aType.GetType();

        var method = type.GetMethod("DoSomething");

        if (method != null)
        {
            MyEvent += method;//How do I wire this up?
        }
    }
}


public class SomeType {
    public void DoSomething() {
        Debug.WriteLine("DoSomething ran.");
    }
}

您需要创建一个委托:

MyEvent += (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), aType, method);
第二个参数是将委托绑定到的实例。
有关详细信息,请参阅


与任何其他委托一样,只有当目标方法与委托具有相同的签名(参数类型)时,这才有效。

实际上,您不能将
DoSomething
用作
MyEvent
的处理程序,因为它没有正确的签名。假设您将
DoSomething
的签名更改为:

public void DoSomething(object sender, EventArgs e)
您可以按如下方式订阅活动:

    if (method != null)
    {
        var dlg = (EventHandler)Delegate.CreateDelegate(typeof(EventHandler), aType, method);
        MyEvent += dlg;
    }

您还需要将CreateDelegate的结果强制转换为EventHandler感谢您的快速响应。这很有帮助。