What use is the Tag property in .net

2019-01-17 16:42发布

问题:

I have noticed the Tag properties with controls. Is it okay to use this to reference my custom objects, or should I stay away from it as it would require boxing and unboxing which has been mentioned as unsafe and is not recomended.

TreeNode tn = new TreeNode ();
CustClass o = new CustClass()
o.number = 123;
tn.Tag = o;

class CustClass
{
    public int number {get; set;}
}

回答1:

The purpose of the Tag property is for you to use it for any purpose you want. You can safely store anything in there you want.

It is customary to declare a class that is specifically intended for being stored in the Tag property (like you did with your CustClass). But if you need only one value in it, then there is nothing wrong with storing an int in it directly.

Where did you read that boxing/unboxing is “unsafe”? That is absolutely not true. (Some people claim that it is inefficient, but even that is not true.) Furthermore, your code does not even contain an example of boxing at all. CustClass is a reference type. Only value types are boxed when assigned to object.



回答2:

I don't think this would be a boxing or unboxing problem to use it the way you want. As far as I know, that Tag property is for the programmer's purpose only, so you can use it quite the way you need it to be used.

Please see Control.Tag property on MSDN for further reference on how to use this property.

For instance, I used to use it to input instructions to the user in Windows Forms applications. When the control GotFocus event triggered, the instructions Label.Text property was assigned the value of my control Tag property which contained the instruction string.



回答3:

From links also mentioned by others here:

at https://msdn.microsoft.com/en-us/library/system.windows.forms.control.tag.aspx one reads:

Any type derived from the Object class can be assigned to this property. If the Tag property is set through the Windows Forms designer, only text can be assigned.

A common use for the Tag property is to store data that is closely associated with the control. For example, if you have a control that displays information about a customer, you might store a DataSet that contains the customer's order history in that control's Tag property so the data can be accessed quickly.

and at https://msdn.microsoft.com/en-us/library/system.windows.forms.treenode.tag.aspx one reads:

...example creates a root tree node to assign child tree nodes to. A child tree node for each Customer object in an ArrayList is added to the root tree node as well as a child tree node for each Order object assigned to the Customer object. The Customer object is assigned to the Tag property, and the tree nodes representing Customer objects are displayed with Orange text. This example requires that you have a Customer and Order object defined, a TreeView control on a Form, and an ArrayList named customerArray that contains Customer objects.