c# - 如何使用 TreeView.Tag = object?

标签 c# .net winforms treeview

像这样:

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

异常还是空值?

最佳答案

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";

如果您尝试访问一个不存在的 key ,一个 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 = object?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11784956/

相关文章:

c#检查文本框中的整数

c# - Newtonsoft.JSON 无法转换具有 TypeConverter 属性的模型

c# - 在 StaticResource Canvas 中为 Path 设置不同的大小或自动调整大小

c# - 在 .NET Speech 中添加另一个声音

c# - 如何将值从一种形式传递到另一种形式?

c# - 难以比较 DateTimes 中的差异

c# - 使用 C# 对 MS office 进行编程 - 可能吗?

c# - 谷歌地图信息窗口显示以前的地理结果而不是当前结果

c# - .NET WCF 服务获取 Blob 的 JSON 列表

c# - .NET : How do you remove a specific node from an XMLDocument using XPATH?