我正在为列表中的每个对象创建一组表单控件,是否可以在控件的 Tag 属性中存储对对象的引用?
我这样做是为了在控件上有一个通用的 Click 事件,这样当它们被单击时我可以更新它们所代表的对象中的一个字段。
所以点击处理程序看起来像这样。
private void Item_Clicked(object sender, system.EventArgs e)
{
if(sender.GetType() == typeof(System.Windows.Forms.Label))
{
System.Windows.Forms.Label label = (System.Windows.Forms.Label)sender;
MyObject myObject = label.Tag;
myObject.Value = true;
}
}
在这种情况下,这是可以接受的做法吗?还是有更好的方法来处理这个问题?
最佳答案
是的,这是合法的,并且是 Tag
属性设计的模式之一。
这里最大的危险是另一段代码试图将相同的 Tag
属性用于他们自己的功能。这将为 Tag
属性创建一个竞争并导致运行时错误。一种更安全的方法是使用 Dictionary
实例在 Label
和 MyObject
之间创建私有(private)映射。
private Dictionary<Label,MyObject> _map = new Dictionary<Label,MyObject>();
...
private void Item_Clicked(object sender, system.EventArgs e)
{
if(sender.GetType() == typeof(System.Windows.Forms.Label))
{
System.Windows.Forms.Label label = (System.Windows.Forms.Label)sender;
MyObject myObject = _map[label];
myObject.Value = true;
}
}
这种方法有 Dictionary
的额外开销,但会生成更可靠的代码(恕我直言)。
关于c# - 正在将对象引用存储在控件的 Tag 属性中 OK,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3927067/