如何使用匿名方法动态订阅事件?
我正在使用 LoadControl(String) 动态创建多个 UserControl,并希望订阅每个用户的事件。
我的所有控件都继承了一个公共接口
,需要实现一个公共事件
:
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!
}
如何订阅此事件的委托?
I'm creating a number of UserControl
s dynamically using LoadControl(String)
and want to subscribe to an event of each of them.
All my controls inherits a common Interface
that require an implementation of a common Event
:
public interface IObjectProcessor
{
event EventHandler<ObjectProcessedEventArgs> ObjectProcessed;
}
So I do next on my page loading event:
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!
}
How to subscribe a deleagte to this event?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
将
Action
更改为EventHandler
:Change
Action<object, ObjectProcessedEventArgs>
toEventHandler<ObjectProcessedEventArgs>
: