正在将对象引用存储在控件标记属性中,正常
我正在为列表中的每个对象创建一组表单控件,是否可以在控件 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;
}
}
在这种情况下这是可以接受的事情,还是有更好的方法来处理这个问题?
I'm creating a group of form controls for each object in a list, is it OK to store a reference to the object in the controls Tag property?
I'm doing this so I can have a generic Click event on the controls, so when they are clicked I can update a field in the object that they represent.
So the click handler will look something like this.
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;
}
}
Is this an acceptable thing to do in this situation, or is there a better way to handle this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,这是合法的,并且是
Tag
属性设计的模式之一。这里最大的危险是另一段代码尝试为自己的功能使用相同的
Tag
属性。这会造成Tag
属性的竞争并导致运行时错误。更安全的方法是使用Dictionary
实例在Label
和MyObject
之间创建私有映射。这种方法具有字典的额外开销,但会产生更可靠的代码(恕我直言)。
Yes this is legal to do and is one of the patterns the
Tag
property was designed for.The biggest danger here is that another peice of code attempts to use the same
Tag
property for their own feature. This would create a race for theTag
property and lead to runtime bugs. A safer approach would be to create a private map between aLabel
andMyObject
using aDictionary
instance.This approach has the extra overhead of a
Dictionary
but produces more reliable code (IMHO).如果它对你有用的话是可以接受的。我之前已经像这样正确地将内容存储在标签中,并且工作正常。需要考虑的事项:您要存储的对象的大小以及对象的生命周期(是否可以在访问之间处理或销毁它)。
我使用的另一种方法是存储一个“提示”,以帮助您检索或重新创建该对象。例如,如果它是一个数据库对象,则存储 Id 属性(可能是整数或 Guid),该属性[可能]比对象本身小得多。
It's acceptable if it works for you. I've stored things in the tag properly like this before, and it works fine. Things to consider: the size of the object you're storing and the lifecyle of the object (could it be disposed of or destroyed between accesses).
Another approach, that I have used, is to store a "hint" that would help you retreive or recreate the object. For example, if it's a database object, store the Id property (maybe an integer or Guid) which is much [potentially] much smaller than the object itself.