访问私有类中的成员
我遇到了一种情况,当我需要访问嵌入式私有类中的类的私有成员时。我怎样才能有效地做到这一点。
public partial class Form1 : Form
{
// this private label will be used only in this form
private class MyFormLabel : Label
{
MyFormLabel()
{
this.BorderStyle = BorderStyle.FixedSingle;
// ?? how to pass the from label_Click (without delegates)?
this.Click +=new EventHandler(????);
}
}
public Form1()
{
InitializeComponent();
}
private void label_Click(object sender, EventArgs e)
{
// displays the form caption
MessageBox.Show(this.Text);
}
}
备注: 我将控件动态添加到表单中,因此我可以确保在创建后它们已经订阅了此事件。
I have a situation when I need to access the private members of a class in an embedded private class. How can I do it efficiently.
public partial class Form1 : Form
{
// this private label will be used only in this form
private class MyFormLabel : Label
{
MyFormLabel()
{
this.BorderStyle = BorderStyle.FixedSingle;
// ?? how to pass the from label_Click (without delegates)?
this.Click +=new EventHandler(????);
}
}
public Form1()
{
InitializeComponent();
}
private void label_Click(object sender, EventArgs e)
{
// displays the form caption
MessageBox.Show(this.Text);
}
}
NotaBene:
I add dynamically the controls to the form, so I would be sure that after creation they are already subscribed to this event.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以从嵌套类访问类的私有成员。当然,要访问实例方法,您仍然需要类的实例。
You can access private members of classes from nested classes. Of course, to access an instance method you still need an instance of the class.
在这种情况下,只需以相反的方式执行即可,例如在
InitializeComponent()
之后执行myFormLabel.Click += label_Click
In this case, just do it the othwe way around, e.g. after
InitializeComponent()
do amyFormLabel.Click += label_Click