您可以通过反射从方法创建委托,然后通过反射将其订阅到事件,是的。示例代码:
using System;
using System.Reflection;
class Publisher
{
public event EventHandler Foo;
public void RaiseFoo()
{
EventHandler handler = Foo;
if (handler != null)
{
handler(this, EventArgs.Empty);
}
}
}
class Subscriber
{
public void HandleEvent(object sender, EventArgs e)
{
Console.WriteLine("In HandleEvent");
}
}
class Test
{
static void Main()
{
var subscriber = new Subscriber();
var publisher = new Publisher();
var methodInfo = typeof(Subscriber).GetMethod("HandleEvent");
var handler = (EventHandler) Delegate.CreateDelegate(
typeof(EventHandler), subscriber, methodInfo);
var eventInfo = typeof(Publisher).GetEvent("Foo");
eventInfo.AddEventHandler(publisher, handler);
publisher.RaiseFoo();
}
}