此屬性用於獲取或設置與指定鍵關聯的值。
用法:
public TValue this[TKey key] { get; set; }
在這裏,key是要獲取或設置的值的Key。
屬性值:與指定鍵關聯的值。如果找不到指定的鍵,則get操作將引發KeyNotFoundException,而set操作將使用指定的鍵創建一個新元素。
異常:
- ArgumentNullException:如果鍵為null。
- KeyNotFoundException:如果檢索到屬性並且鍵在集合中不存在。
例:
// C# code to get or set the value
// associated with the specified key
using System;
using System.Collections;
using System.Collections.Generic;
class GFG {
// Driver code
public static void Main()
{
// Creating a SortedDictionary named myDict
SortedDictionary<string, string> myDict =
new SortedDictionary<string, string>();
// Adding key/value pairs in myDict
myDict.Add("Australia", "Canberra");
myDict.Add("Belgium", "Brussels");
myDict.Add("Netherlands", "Amsterdam");
myDict.Add("China", "Beijing");
myDict.Add("Russia", "Moscow");
myDict.Add("India", "New Delhi");
// Displaying the key/value pairs in myDict
foreach(KeyValuePair<string, string> k in myDict)
{
Console.WriteLine("Key = {0}, Value = {1}",
k.Key, k.Value);
}
// Displaying the value associated
// with key "Russia"
Console.Write("\nValue associated with Russia:");
Console.Write(myDict["Russia"]);
// Setting the value associated with key "Russia"
myDict["Russia"] = "Saint Petersburg";
// Displaying the value associated
// with key "Russia"
Console.Write("\n\nValue associated with"+
" Russia After Setting:");
Console.Write(myDict["Russia"]);
// Displaying the value associated
// with key "India"
Console.Write("\n\nValue associated with India:");
Console.Write(myDict["India"]);
// Setting the value associated with key "India"
myDict["India"] = "Mumbai";
// Displaying the value associated
// with key "India"
Console.Write("\n\nValue associated "+
"with India After Setting:");
Console.Write(myDict["India"]);
Console.WriteLine("\n");
// Displaying the key/value pairs in myDict
foreach(KeyValuePair<string, string> k1 in myDict)
{
Console.WriteLine("Key = {0}, Value = {1}",
k1.Key, k1.Value);
}
}
}
輸出:
Key = Australia, Value = Canberra Key = Belgium, Value = Brussels Key = China, Value = Beijing Key = India, Value = New Delhi Key = Netherlands, Value = Amsterdam Key = Russia, Value = Moscow Value associated with Russia:Moscow Value associated with Russia After Setting:Saint Petersburg Value associated with India:New Delhi Value associated with India After Setting:Mumbai Key = Australia, Value = Canberra Key = Belgium, Value = Brussels Key = China, Value = Beijing Key = India, Value = Mumbai Key = Netherlands, Value = Amsterdam Key = Russia, Value = Saint Petersburg
參考:
相關用法
- C# Dictionary.Values用法及代碼示例
- C# Dictionary.Item[]用法及代碼示例
- C# SortedDictionary.Values用法及代碼示例
- C# SortedDictionary.Keys用法及代碼示例
- C# SortedDictionary.Count用法及代碼示例
- C# Dictionary.Keys用法及代碼示例
- C# Dictionary.Count用法及代碼示例
- C# Queue.Count用法及代碼示例
- C# Queue.IsSynchronized用法及代碼示例
- C# Stack.Count用法及代碼示例
- C# Stack.IsSynchronized用法及代碼示例
注:本文由純淨天空篩選整理自Kirti_Mangal大神的英文原創作品 C# | SortedDictionary.Item[] Property。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。