Dictionary<TKey,TValue>.Item[TKey] 属性

定义

获取或设置与指定的键关联的值。

C#
public TValue this[TKey key] { get; set; }

参数

key
TKey

要获取或设置的值的键。

属性值

TValue

与指定的键相关联的值。 如果找不到指定的键,get 操作便会引发 KeyNotFoundException,而 set 操作会创建一个具有指定键的新元素。

实现

例外

keynull

已检索该属性且集合中不存在 key

示例

下面的代码示例使用 Item[] C#) 中索引器 (属性来检索值,演示 KeyNotFoundException 当请求的键不存在时会引发 ,并显示可以替换与键关联的值。

该示例还演示了如果程序经常必须尝试不在字典中的键值,则 TryGetValue 如何使用 方法作为检索值的更有效方法。

此代码示例是为 Dictionary<TKey,TValue> 类提供的一个更大示例的一部分。 openWith 是此示例中使用的字典的名称。

C#
// Create a new dictionary of strings, with string keys.
//
Dictionary<string, string> openWith =
    new Dictionary<string, string>();

// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");

// The Add method throws an exception if the new key is
// already in the dictionary.
try
{
    openWith.Add("txt", "winword.exe");
}
catch (ArgumentException)
{
    Console.WriteLine("An element with Key = \"txt\" already exists.");
}
C#
// The Item property is another name for the indexer, so you
// can omit its name when accessing elements.
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] = "winword.exe";
Console.WriteLine("For key = \"rtf\", value = {0}.",
    openWith["rtf"]);

// If a key does not exist, setting the indexer for that key
// adds a new key/value pair.
openWith["doc"] = "winword.exe";
C#
// The indexer throws an exception if the requested key is
// not in the dictionary.
try
{
    Console.WriteLine("For key = \"tif\", value = {0}.",
        openWith["tif"]);
}
catch (KeyNotFoundException)
{
    Console.WriteLine("Key = \"tif\" is not found.");
}
C#
// When a program often has to try keys that turn out not to
// be in the dictionary, TryGetValue can be a more efficient
// way to retrieve values.
string value = "";
if (openWith.TryGetValue("tif", out value))
{
    Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console.WriteLine("Key = \"tif\" is not found.");
}

注解

此属性提供使用以下 C# 语法访问集合中的特定元素的功能: myCollection[key] Visual Basic) 中的 (myCollection(key)

还可以使用 Item[] 属性通过设置 中 Dictionary<TKey,TValue>不存在的键的值来添加新元素。 设置属性值时,如果键位于 中 Dictionary<TKey,TValue>,则与该键关联的值将替换为分配的值。 如果 键不在 中 Dictionary<TKey,TValue>,则键和值将添加到字典中。 相反, Add 方法不修改现有元素。

如果值类型是 null引用类型 TValue ,则键不能为 ,但值可以是 。

C# 语言使用 this 关键字来定义索引器,而不是实现 Item[] 属性。 Visual Basic 将 Item[] 实现为默认属性,该属性提供相同的索引功能。

获取或设置此属性的值将接近 O (1) 操作。

适用于

产品 版本
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.0, 1.1, 1.2, 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

另请参阅