如何从该标签中获得具有标签控件的类的对象引用
本文关键字:标签 控件 对象引用 | 更新日期: 2023-09-27 17:49:01
我有一个类,它有一个Label字段。现在我想从那个标签中得到那个类的引用。我怎么能做到呢?
public class Abc
{
Label l;
}
public partial class Form1 : Form
{
private void btnins_Click(object sender, EventArgs e)
{
Abc ob=new Abc();
ob.l=new new Label();
l.Text="Right Click Me";
l.ContextMenuStrip = cntxtdelmnu;
}
private void cntxtdelnode_Click(object sender, EventArgs e)
{
Label lbl= (Label)cntxtdelmnu.SourceControl;
//Here I have to get the reference of ob using lbl.
}
}
基本上不能。可以有多个对象引用该标签-或者根本没有。你不能得到一个"向后"的参考。您可以将引用存储在Tag
属性中:
Abc ob=new Abc();
ob.l= new Label();
ob.l.Text="Right Click Me";
ob.l.ContextMenuStrip = cntxtdelmnu;
ob.l.Tag = ob;
或者使用对象初始化式:
Abc ob = new Abc();
ob.l = new Label { Text = "Right Click Me", ContextMenuStrip = cntxtdelmnu, Tag = ob };
我会尝试避免需要。从这个问题上看不出你为什么想要它,但可能有更好的方法。(我真希望那不是你们的真名…)