Dictionary<TKey,TValue>.Item[TKey] Dictionary<TKey,TValue>.Item[TKey] Dictionary<TKey,TValue>.Item[TKey] Dictionary<TKey,TValue>.Item[TKey] Property

定義

取得或設定與指定之索引鍵相關聯的值。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 TKey TKey TKey

要取得或設定之值的索引鍵。The key of the value to get or set.

屬性值

TValue TValue TValue TValue

與指定之索引鍵關聯的值。The value associated with the specified key. 如果找不到指定的索引鍵,則取得作業會擲回 KeyNotFoundException,且設定作業會使用指定的索引鍵建立新項目。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.

實作

例外狀況

會擷取屬性,且 key 不存在於集合中。The 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.

如果實值型null TValue別是引用型別,則索引鍵不能是,但值可以是。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.

適用於

另請參閱