如何使用匿名方法动态订阅事件?

时间:2009-08-14 14:34:16

标签: c# .net asp.net delegates anonymous-methods

我正在使用UserControl动态创建一些LoadControl(String),并希望订阅每个Interface的事件。

我的所有控件都会继承一个需要实现公共Event的公共public interface IObjectProcessor { event EventHandler<ObjectProcessedEventArgs> ObjectProcessed; }

protected void Page_Load()
{
   switch(Request["type"])
   {
     case "user":
     {
        LoadControl("AddUser.ascx", delegate(object sender, ObjectProcessedEventArgs e)
        {
           // do something
        });
        break;
     }
   }
}

private void LoadControl(string path, Action<object, ObjectProcessedEventArgs> action)
{
    var control = (IObjectProcessor)LoadControl(path)
    control.ObjectProcessed // here!
}

所以我在我的页面加载事件中做下一步:

{{1}}

如何订阅此事件的删除?

2 个答案:

答案 0 :(得分:5)

Action<object, ObjectProcessedEventArgs>更改为EventHandler<ObjectProcessedEventArgs>

private void LoadControl(string path, EventHandler<ObjectProcessedEventArgs> handler)
{
        var control = (IObjectProcessor)LoadControl(path)
        control.ObjectProcessed += handler;
}

答案 1 :(得分:-1)

control.ObjectProcessed += action