像这样:
Dictionary<int, string> myData = new Dictionary<int, string>();
myData.Add(1, "England");
myData.Add(2, "Canada");
myData.Add(3, "Australia");
myTreeView.Node[0].Tag = myData;
然后我想得到这个物体,该怎么办?
喜欢:
string str = new string();
str = myTreeView.Node[0].Tag[2]; // "str" should be equal to "Canada"
myTreeView.Node[0].Tag[1] = "Spain";
str = myTreeView.Node[0].Tag[1]; // now "str" is equal to "Spain"
第二个问题-什么将返回此表达式:
Dictionary<int, string> myData = new Dictionary<int, string>();
myData.Add(1, "England");
myData.Add(2, "Canada");
myData.Add(3, "Australia");
string str1 = new string();
str = myData[4]; // there isn't such a key as 4
异常还是null?
最佳答案
Control.Tag
键入为object
,因此您需要将其强制转换为以Dictionary<int, string>
身份访问:
Dictionary<int, string> dict = (Dictionary<int, string>)myTreeView.Node[0].Tag;
string str = dict[2];
并类似地设置一个值:
var dict = (Dictionary<int, string>)myTreeView.Node[0].Tag;
dict[1] = "Spain";
如果您尝试访问不存在的密钥,将抛出
KeyNotFoundException
。您可以使用TryGetValue
或ContainsKey
检查词典是否包含给定键:if(dict.ContainsKey(key))
{
var value = dict[key];
}
else
{
}
TryGetValue进行查找,并在一次调用中将给定变量设置为值(它存在),因此通常是首选方法。
string value;
if(dict.TryGetValue(key, out value))
{
//use value
}
else { ... }
关于c# - 如何使用TreeView.Tag =对象?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11784956/