IDictionary<TKey,TValue> 介面
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
表示索引鍵/值組的泛型集合。
generic <typename TKey, typename TValue>
public interface class IDictionary : System::Collections::Generic::ICollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>>
public interface IDictionary<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>
type IDictionary<'Key, 'Value> = interface
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IEnumerable
Public Interface IDictionary(Of TKey, TValue)
Implements ICollection(Of KeyValuePair(Of TKey, TValue)), IEnumerable(Of KeyValuePair(Of TKey, TValue))
類型參數
- TKey
字典中的索引鍵類型。
- TValue
字典中的值類型。
- 衍生
- 實作
-
ICollection<KeyValuePair<TKey,TValue>> IEnumerable<KeyValuePair<TKey,TValue>> IEnumerable<T> IEnumerable
範例
下列程式代碼範例會使用字串索引鍵建立空的字串 Dictionary<TKey,TValue>,並透過 IDictionary<TKey,TValue> 介面加以存取。
程式代碼範例會使用 Add 方法來新增一些元素。 此範例示範嘗試新增重複索引鍵時,Add 方法會擲回 ArgumentException。
此範例會使用 Item[] 屬性 (C# 中的索引器) 來擷取值,示範當要求索引鍵不存在時擲回 KeyNotFoundException,並顯示可以取代與索引鍵相關聯的值。
此範例示範如何使用 TryGetValue 方法,以更有效率的方式擷取值,如果程式通常必須嘗試不在字典中的索引鍵值,以及如何使用 ContainsKey 方法來測試索引鍵是否存在,然後再呼叫 Add 方法。
最後,此範例示範如何列舉字典中的索引鍵和值,以及如何使用 Values 屬性單獨列舉值。
using namespace System;
using namespace System::Collections::Generic;
public ref class Example
{
public:
static void Main()
{
// Create a new dictionary of strings, with string keys,
// and access it through the IDictionary generic interface.
IDictionary<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.");
}
// 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 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.");
}
// 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.");
}
// ContainsKey can be used to test keys before inserting
// them.
if (!openWith->ContainsKey("ht"))
{
openWith->Add("ht", "hypertrm.exe");
Console::WriteLine("Value added for key = \"ht\": {0}",
openWith["ht"]);
}
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console::WriteLine();
for each( KeyValuePair<String^, String^> kvp in openWith )
{
Console::WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
ICollection<String^>^ icoll = openWith->Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console::WriteLine();
for each( String^ s in icoll )
{
Console::WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
icoll = openWith->Keys;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console::WriteLine();
for each( String^ s in icoll )
{
Console::WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair.
Console::WriteLine("\nRemove(\"doc\")");
openWith->Remove("doc");
if (!openWith->ContainsKey("doc"))
{
Console::WriteLine("Key \"doc\" is not found.");
}
}
};
int main()
{
Example::Main();
}
/* This code example produces the following output:
An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe
Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht
Remove("doc")
Key "doc" is not found.
*/
using System;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new dictionary of strings, with string keys,
// and access it through the IDictionary generic interface.
IDictionary<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.");
}
// 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 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.");
}
// 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.");
}
// ContainsKey can be used to test keys before inserting
// them.
if (!openWith.ContainsKey("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}",
openWith["ht"]);
}
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
Console.WriteLine();
foreach( KeyValuePair<string, string> kvp in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
kvp.Key, kvp.Value);
}
// To get the values alone, use the Values property.
ICollection<string> icoll = openWith.Values;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in icoll )
{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
icoll = openWith.Keys;
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
Console.WriteLine();
foreach( string s in icoll )
{
Console.WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair.
Console.WriteLine("\nRemove(\"doc\")");
openWith.Remove("doc");
if (!openWith.ContainsKey("doc"))
{
Console.WriteLine("Key \"doc\" is not found.");
}
}
}
/* This code example produces the following output:
An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
Key = "tif" is not found.
Key = "tif" is not found.
Value added for key = "ht": hypertrm.exe
Key = txt, Value = notepad.exe
Key = bmp, Value = paint.exe
Key = dib, Value = paint.exe
Key = rtf, Value = winword.exe
Key = doc, Value = winword.exe
Key = ht, Value = hypertrm.exe
Value = notepad.exe
Value = paint.exe
Value = paint.exe
Value = winword.exe
Value = winword.exe
Value = hypertrm.exe
Key = txt
Key = bmp
Key = dib
Key = rtf
Key = doc
Key = ht
Remove("doc")
Key "doc" is not found.
*/
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new dictionary of strings, with string keys,
' and access it through the IDictionary generic interface.
Dim openWith As IDictionary(Of String, String) = _
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 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 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.
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
' ContainsKey can be used to test keys before inserting
' them.
If Not openWith.ContainsKey("ht") Then
openWith.Add("ht", "hypertrm.exe")
Console.WriteLine("Value added for key = ""ht"": {0}", _
openWith("ht"))
End If
' When you use foreach to enumerate dictionary elements,
' the elements are retrieved as KeyValuePair objects.
Console.WriteLine()
For Each kvp As KeyValuePair(Of String, String) In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
kvp.Key, kvp.Value)
Next kvp
' To get the values alone, use the Values property.
Dim icoll As ICollection(Of String) = openWith.Values
' The elements of the ValueCollection are strongly typed
' with the type that was specified for dictionary values.
Console.WriteLine()
For Each s As String In icoll
Console.WriteLine("Value = {0}", s)
Next s
' To get the keys alone, use the Keys property.
icoll = openWith.Keys
' The elements of the ValueCollection are strongly typed
' with the type that was specified for dictionary values.
Console.WriteLine()
For Each s As String In icoll
Console.WriteLine("Key = {0}", s)
Next s
' Use the Remove method to remove a key/value pair.
Console.WriteLine(vbLf + "Remove(""doc"")")
openWith.Remove("doc")
If Not openWith.ContainsKey("doc") Then
Console.WriteLine("Key ""doc"" is not found.")
End If
End Sub
End Class
' This code example produces the following output:
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'Key = "tif" is not found.
'Key = "tif" is not found.
'Value added for key = "ht": hypertrm.exe
'
'Key = txt, Value = notepad.exe
'Key = bmp, Value = paint.exe
'Key = dib, Value = paint.exe
'Key = rtf, Value = winword.exe
'Key = doc, Value = winword.exe
'Key = ht, Value = hypertrm.exe
'
'Value = notepad.exe
'Value = paint.exe
'Value = paint.exe
'Value = winword.exe
'Value = winword.exe
'Value = hypertrm.exe
'
'Key = txt
'Key = bmp
'Key = dib
'Key = rtf
'Key = doc
'Key = ht
'
'Remove("doc")
'Key "doc" is not found.
'
備註
IDictionary<TKey,TValue> 介面是索引鍵/值組泛型集合的基底介面。
每個元素都是儲存在 KeyValuePair<TKey,TValue> 物件中的索引鍵/值組。
每個配對都必須有唯一索引鍵。 實作可能會因是否允許 key
null
而有所不同。 此值可以是 null
,而且不一定是唯一的。
IDictionary<TKey,TValue> 介面允許列舉包含的索引鍵和值,但並不代表任何特定的排序順序。
C# 語言的 foreach
語句(在 Visual Basic 中為For Each
,for each
C++) 會傳回集合中專案類型的 物件。 由於 IDictionary<TKey,TValue> 的每個元素都是索引鍵/值組,因此項目類型不是索引鍵的類型或值的型別。 相反地,元素類型會 KeyValuePair<TKey,TValue>。 例如:
for each(KeyValuePair<int, String^> kvp in myDictionary)
{
Console::WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
foreach (KeyValuePair<int, string> kvp in myDictionary)
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
For Each kvp As KeyValuePair(Of Integer, String) In myDictionary
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value)
Next kvp
foreach
語句是列舉值周圍的包裝函式,它只允許讀取集合,而不是寫入集合。
注意
因為索引鍵可以繼承並變更其行為,所以使用 Equals 方法的比較無法保證其絕對唯一性。
給實施者的注意事項
實作類別必須有比較索引鍵的方法。
屬性
Count |
取得包含在 ICollection<T>中的項目數目。 (繼承來源 ICollection<T>) |
IsReadOnly |
取得值,指出 ICollection<T> 是否為唯讀。 (繼承來源 ICollection<T>) |
Item[TKey] |
取得或設定具有指定索引鍵的專案。 |
Keys |
取得包含 IDictionary<TKey,TValue>索引鍵的 ICollection<T>。 |
Values |
取得 ICollection<T>,其中包含 IDictionary<TKey,TValue>中的值。 |
方法
Add(T) |
將專案加入至 ICollection<T>。 (繼承來源 ICollection<T>) |
Add(TKey, TValue) |
將具有所提供索引鍵和值的專案加入至 IDictionary<TKey,TValue>。 |
Clear() |
從 ICollection<T>移除所有專案。 (繼承來源 ICollection<T>) |
Contains(T) |
判斷 ICollection<T> 是否包含特定值。 (繼承來源 ICollection<T>) |
ContainsKey(TKey) |
判斷 IDictionary<TKey,TValue> 是否包含具有指定索引鍵的專案。 |
CopyTo(T[], Int32) |
從特定 Array 索引開始,將 ICollection<T> 的專案複製到 Array。 (繼承來源 ICollection<T>) |
GetEnumerator() |
傳回逐一查看集合的列舉值。 (繼承來源 IEnumerable) |
Remove(TKey) |
從 IDictionary<TKey,TValue>移除具有指定索引鍵的專案。 |
TryGetValue(TKey, TValue) |
取得與指定索引鍵相關聯的值。 |