SortedDictionary<TKey,TValue>.Item[TKey] 屬性

定義

取得或設定與指定之索引鍵相關聯的值。

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

參數

key
TKey

要取得或設定之值的索引鍵。

屬性值

TValue

與指定之索引鍵關聯的值。 如果找不到指定的索引鍵,則取得作業會擲回 KeyNotFoundException,且設定作業會使用指定的索引鍵建立新項目。

實作

例外狀況

keynull

會擷取該屬性,而且 key 不存在於集合中。

範例

下列程式代碼範例會 Item[] 使用 屬性 (C#) 中的索引器來擷取值,示範 KeyNotFoundException 當要求的索引鍵不存在時擲回 ,並顯示可以取代與索引鍵相關聯的值。

如果程式通常必須嘗試不在字典中的索引鍵值,此範例也會示範如何使用 TryGetValue 方法作為更有效率的方式來擷取值。

此程式代碼範例是提供給 類別之較大範例的 SortedDictionary<TKey,TValue> 一部分。

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] (myCollection(key) Visual Basic) 。

您也可以藉由設定不存在於 中的SortedDictionary<TKey,TValue>索引鍵值,來使用 Item[] 屬性來加入新元素,例如 myCollection["myNonexistentKey"] = myValue。 不過,如果指定的索引鍵已存在於 中 SortedDictionary<TKey,TValue>,則設定 Item[] 屬性會覆寫舊值。 相反地, Add 方法不會修改現有的專案。

如果實值型別是參考型TValue別,索引鍵不能是 null,但值可以是 。

C# 語言會使用此 關鍵詞來定義索引器,而不是實作 Item[] 屬性。 Visual Basic 會將 Item[] 實作為預設屬性,這樣會提供相同的索引功能。

取得此屬性的值是 O (記錄 n) 作業;設定屬性也是 O (記錄 n) 作業。

適用於

產品 版本
.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

另請參閱