是否可以在.NET中将类的成员对象的事件暴露给外部? [英] Is it possible to expose events of a member object of a class to the outside in .NET?

查看:80
本文介绍了是否可以在.NET中将类的成员对象的事件暴露给外部?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我在ASP.NET中有一个包含按钮的用户控件:

Say I have a User Control in ASP.NET that contains a button:

public class MyUserControl : UserControl {
    private Button btnSave = new Button();
}

我可以通过创建指向按钮的属性来将按钮的任何属性暴露给外部:

I can expose any property of the button to the outside by making a property that points at the button:

public string SaveButtonText { 
    get { return btnSave.Text; } 
    set { btnSave.Text = value; } 
}

因此,我可以执行以下操作来设置按钮的文本:

So then I can do this to set the button's text:

MyControl.SaveButtonText = "hello world";

我是否可以使用类似的构造将按钮的事件暴露给外部?像这样:

Is there a similar construct I can use to expose the button's events to the outside as well? Something like:

public event SaveButtonClick { return btnSave.OnClick; }
...
MyControl.SaveButtonClick += new EventHandler(...);

推荐答案

您可以做类似的事情,是的:

You can do something like that, yes:

public event EventHandler SaveButtonClick
{
    add { btnSave.Click += value; }
    remove { btnSave.Click -= value; }
}

但是请注意,这样做有一个缺点-提供给事件处理程序的"sender"参数仍然是保存按钮,而不是您的控件...这可能不是订阅者所期望的.另一种方法是自己订阅一次保存按钮的点击处理程序:

Note however that there's one downside to this - the "sender" argument supplied to the event handlers will still be the save button rather than your control... that may not be what the subscriber expected. An alternative approach is to subscribe once to the save button's click handler yourself:

public event EventHandler SaveButtonClick = delegate {};

private void OnSaveButtonClicked(object sender, EventArgs e)
{
    // Replace the original sender with "this"
    SaveButtonClick(this, e);
}
...
btnSave.Click += OnSaveButtonClicked();

此方法也有一个弊端……您最终总是从保存"按钮获得对此"的引用,这可能会产生影响.在垃圾收集上.基本上,直到保存按钮也可以进行垃圾收集之前,您的控件才能被垃圾收集.在这种情况下,我非常怀疑这是一个问题,但是值得注意.

There's a downside to this approach too... you end up having a reference from the save button to "this" all the time, which may have an impact on garbage collection. Basically your control won't be able to be garbage collected until the save button is also eligible for garbage collection. In this case I very much doubt that it's an issue, but it's worth being aware of.

这篇关于是否可以在.NET中将类的成员对象的事件暴露给外部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆