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

定义

获取或设置与指定的键关联的值。Gets or sets the value associated with the specified key.

public:
 property TValue default[TKey] { TValue get(TKey key); void set(TKey key, TValue value); };
public TValue this[TKey key] { get; set; }
member this.Item('Key) : 'Value with get, set
Default Public Property Item(key As TKey) As TValue

参数

key
TKey

要获取或设置的值的键。The key of the value to get or set.

属性值

TValue

与指定的键相关联的值。The value associated with the specified key. 如果找不到指定的键,get 操作便会引发 KeyNotFoundException,而 set 操作会创建一个具有指定键的新元素。If the specified key is not found, a get operation throws a KeyNotFoundException, and a set operation creates a new element with the specified key.

实现

异常

keynullkey is null.

已检索该属性,并且集合中不存在 keyThe property is retrieved and key does not exist in the collection.

示例

备注

本文中的一些 C# 示例在 Try.NET 内联代码运行程序和演练环境中运行。Some of the C# examples in this article run in the Try.NET inline code runner and playground. 选择“运行” 按钮(若有),在交互式窗口中运行示例。When present, select the Run button to run an example in an interactive window. 执行代码后,可通过再次选择“运行”来修改它并运行已修改的代码 。Once you execute the code, you can modify it and run the modified code by selecting Run again. 已修改的代码要么在交互窗口中运行,要么编译失败时,交互窗口将显示所有 C# 编译器错误消息。The modified code either runs in the interactive window or, if compilation fails, the interactive window displays all C# compiler error messages.

下面的代码示例使用Item[TKey]属性(中C#的索引器)来检索值,演示在请求KeyNotFoundException的键不存在时引发的,并显示与键关联的值可以替换。The following code example uses the Item[TKey] property (the indexer in C#) to retrieve values, demonstrating that a KeyNotFoundException is thrown when a requested key is not present, and showing that the value associated with a key can be replaced.

该示例还演示了如何使用TryGetValue方法作为一种更有效的方法来检索值(如果程序经常需要尝试不在字典中的键值)。The example also shows how to use the TryGetValue method as a more efficient way to retrieve values if a program often must try key values that are not in the dictionary.

此代码示例是为Dictionary<TKey,TValue>类提供的更大示例的一部分。This code example is part of a larger example provided for the Dictionary<TKey,TValue> class. openWith在此示例中使用的字典的名称。openWith is the name of the Dictionary used in this example.

// Create a new dictionary of strings, with string keys.
//
Dictionary<String^, String^>^ openWith =
    gcnew 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.");
}
// 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.");
}
' Create a new dictionary of strings, with string keys.
'
Dim openWith As New Dictionary(Of 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 
    Console.WriteLine("An element with Key = ""txt"" already exists.")
End Try
// 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";
// 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";
' The Item property is the default property, so you 
' can omit its name when accessing elements. 
Console.WriteLine("For key = ""rtf"", value = {0}.", _
    openWith("rtf"))

' The default Item property 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 default Item property
' for that key adds a new key/value pair.
openWith("doc") = "winword.exe"
// 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.");
}
// 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.");
}
' The default Item property throws an exception if the requested
' key is not in the dictionary.
Try
    Console.WriteLine("For key = ""tif"", value = {0}.", _
        openWith("tif"))
Catch 
    Console.WriteLine("Key = ""tif"" is not found.")
End Try
// 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", value))
{
    Console::WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
    Console::WriteLine("Key = \"tif\" is not found.");
}
// 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.");
}
' 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.
Dim value As String = ""
If openWith.TryGetValue("tif", value) Then
    Console.WriteLine("For key = ""tif"", value = {0}.", value)
Else
    Console.WriteLine("Key = ""tif"" is not found.")
End If

注解

此属性提供了使用以下C#语法访问集合中的特定元素的功能: myCollection[key]myCollection(key)在 Visual Basic 中)。This property provides the ability to access a specific element in the collection by using the following C# syntax: myCollection[key] (myCollection(key) in Visual Basic).

你还可以使用Item[TKey]属性来添加新元素,方法是设置Dictionary<TKey,TValue>中不存在的键的值。You can also use the Item[TKey] property to add new elements by setting the value of a key that does not exist in the Dictionary<TKey,TValue>. 设置属性值时,如果键在中Dictionary<TKey,TValue>,则与该键关联的值将替换为指定的值。When you set the property value, if the key is in the Dictionary<TKey,TValue>, the value associated with that key is replaced by the assigned value. 如果键不在中Dictionary<TKey,TValue>,则键和值将添加到字典中。If the key is not in the Dictionary<TKey,TValue>, the key and value are added to the dictionary. 与此Add相反,方法不会修改现有元素。In contrast, the Add method does not modify existing elements.

如果值类型TValuenull引用类型,则键不能为,但值可以为。A key cannot be null, but a value can be, if the value type TValue is a reference type.

该C#语言使用this关键字来定义索引器, Item[TKey]而不是实现属性。The C# language uses the this keyword to define the indexers instead of implementing the Item[TKey] property. Visual Basic 将 Item[TKey] 实现为默认属性,该属性提供相同的索引功能。Visual Basic implements Item[TKey] as a default property, which provides the same indexing functionality.

获取或设置此属性的值将接近 O (1)操作。Getting or setting the value of this property approaches an O(1) operation.

适用于

另请参阅