Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
168 views
in Technique[技术] by (71.8m points)

c# - What use is the Tag property in .net

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;}
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...