如何在C#中访问Dictionary <TKey,TValue> .Item属性

Wol*_*olf 5 .net c# dictionary properties

我是C#/ .Net的新手,并且遇到类Dictionary的问题.我创建了一个组字典并添加了一个项目(或更多项目,现在没关系):

Dictionary<int, ListViewGroup> groups = new Dictionary<int, ListViewGroup>();
groups.Add(1, new ListViewGroup("Group1"));
Run Code Online (Sandbox Code Playgroud)

我想通过它的钥匙找到我的小组.在文档中,它说有一个Item属性,我可以直接访问或通过索引器访问.但是,当我尝试直接访问它时:

ListViewGroup g = groups.Item(1);
Run Code Online (Sandbox Code Playgroud)

我的编译器说在Dictionary类中没有属性Item的定义.有人能解释一下吗?谢谢.

Ily*_*nov 9

Item是一个索引器,您可以通过查看定义来验证它:

public TValue this[TKey key] { get; set; }
Run Code Online (Sandbox Code Playgroud)

只需使用索引器语法按键访问元素:

ListViewGroup g = groups[1]; 
Console.WriteLine (g.Header); //prints Group1 
Run Code Online (Sandbox Code Playgroud)

注意:KeyNotFoundException如果groups词典中不存在带有此类键的条目,则会抛出此值.例如,groups[2]将在您的情况下抛出异常.