Dictionary<TKey,TValue> 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
表示索引鍵和值的集合。
generic <typename TKey, typename TValue>
public ref class Dictionary : System::Collections::Generic::ICollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IDictionary<TKey, TValue>, System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IReadOnlyCollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IReadOnlyDictionary<TKey, TValue>, System::Collections::IDictionary
generic <typename TKey, typename TValue>
public ref class Dictionary : System::Collections::Generic::ICollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IDictionary<TKey, TValue>, System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IReadOnlyCollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IReadOnlyDictionary<TKey, TValue>, System::Collections::IDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
generic <typename TKey, typename TValue>
public ref class Dictionary : System::Collections::Generic::ICollection<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::Generic::IDictionary<TKey, TValue>, System::Collections::Generic::IEnumerable<System::Collections::Generic::KeyValuePair<TKey, TValue>>, System::Collections::IDictionary, System::Runtime::Serialization::IDeserializationCallback, System::Runtime::Serialization::ISerializable
public class Dictionary<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IDictionary<TKey,TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>, System.Collections.IDictionary
public class Dictionary<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IDictionary<TKey,TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class Dictionary<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IDictionary<TKey,TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
[System.Runtime.InteropServices.ComVisible(false)]
[System.Serializable]
public class Dictionary<TKey,TValue> : System.Collections.Generic.ICollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IDictionary<TKey,TValue>, System.Collections.Generic.IEnumerable<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyCollection<System.Collections.Generic.KeyValuePair<TKey,TValue>>, System.Collections.Generic.IReadOnlyDictionary<TKey,TValue>, System.Collections.IDictionary, System.Runtime.Serialization.IDeserializationCallback, System.Runtime.Serialization.ISerializable
type Dictionary<'Key, 'Value> = class
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IEnumerable
interface IDictionary<'Key, 'Value>
interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
interface IReadOnlyDictionary<'Key, 'Value>
interface ICollection
interface IDictionary
type Dictionary<'Key, 'Value> = class
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IEnumerable
interface IDictionary<'Key, 'Value>
interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
interface IReadOnlyDictionary<'Key, 'Value>
interface ICollection
interface IDictionary
interface IDeserializationCallback
interface ISerializable
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type Dictionary<'Key, 'Value> = class
interface IDictionary<'Key, 'Value>
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IDictionary
interface ICollection
interface IEnumerable
interface ISerializable
interface IDeserializationCallback
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type Dictionary<'Key, 'Value> = class
interface IDictionary<'Key, 'Value>
interface ICollection<KeyValuePair<'Key, 'Value>>
interface IDictionary
interface ICollection
interface IReadOnlyDictionary<'Key, 'Value>
interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IEnumerable
interface ISerializable
interface IDeserializationCallback
[<System.Runtime.InteropServices.ComVisible(false)>]
[<System.Serializable>]
type Dictionary<'Key, 'Value> = class
interface IDictionary<'Key, 'Value>
interface ICollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IEnumerable
interface IDictionary
interface ICollection
interface IReadOnlyDictionary<'Key, 'Value>
interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
interface ISerializable
interface IDeserializationCallback
type Dictionary<'Key, 'Value> = class
interface IDictionary<'Key, 'Value>
interface ICollection<KeyValuePair<'Key, 'Value>>
interface IReadOnlyDictionary<'Key, 'Value>
interface IReadOnlyCollection<KeyValuePair<'Key, 'Value>>
interface seq<KeyValuePair<'Key, 'Value>>
interface IDictionary
interface ICollection
interface IEnumerable
Public Class Dictionary(Of TKey, TValue)
Implements ICollection(Of KeyValuePair(Of TKey, TValue)), IDictionary, IDictionary(Of TKey, TValue), IEnumerable(Of KeyValuePair(Of TKey, TValue)), IReadOnlyCollection(Of KeyValuePair(Of TKey, TValue)), IReadOnlyDictionary(Of TKey, TValue)
Public Class Dictionary(Of TKey, TValue)
Implements ICollection(Of KeyValuePair(Of TKey, TValue)), IDeserializationCallback, IDictionary, IDictionary(Of TKey, TValue), IEnumerable(Of KeyValuePair(Of TKey, TValue)), IReadOnlyCollection(Of KeyValuePair(Of TKey, TValue)), IReadOnlyDictionary(Of TKey, TValue), ISerializable
Public Class Dictionary(Of TKey, TValue)
Implements ICollection(Of KeyValuePair(Of TKey, TValue)), IDeserializationCallback, IDictionary, IDictionary(Of TKey, TValue), IEnumerable(Of KeyValuePair(Of TKey, TValue)), ISerializable
類型參數
- TKey
字典中索引鍵的類型。
- TValue
字典中值的型別。
- 繼承
-
Dictionary<TKey,TValue>
- 衍生
- 屬性
- 實作
-
ICollection<KeyValuePair<TKey,TValue>> IDictionary<TKey,TValue> IEnumerable<KeyValuePair<TKey,TValue>> IEnumerable<T> IReadOnlyCollection<KeyValuePair<TKey,TValue>> IReadOnlyDictionary<TKey,TValue> ICollection IDictionary IEnumerable IDeserializationCallback ISerializable
範例
下列程式代碼範例會使用字串索引鍵建立空的字串 Dictionary<TKey,TValue>,並使用 Add 方法來新增某些元素。 此範例示範嘗試新增重複索引鍵時,Add 方法會擲回 ArgumentException。
此範例會使用 Item[] 屬性 (C# 中的索引器) 來擷取值,示範當要求索引鍵不存在時擲回 KeyNotFoundException,並顯示可以取代與索引鍵相關聯的值。
此範例示範如何使用 TryGetValue 方法,以更有效率的方式擷取值,如果程式經常必須嘗試不在字典中的索引鍵值,並示範如何使用 ContainsKey 方法來測試索引鍵是否存在,然後再呼叫 Add 方法。
此範例示範如何列舉字典中的索引鍵和值,以及如何單獨使用 Keys 屬性和 Values 屬性列舉索引鍵和值。
最後,此範例示範 Remove 方法。
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.
//
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.");
}
// 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.
Dictionary<String^, String^>::ValueCollection^ valueColl =
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 valueColl )
{
Console::WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<String^, String^>::KeyCollection^ keyColl =
openWith->Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console::WriteLine();
for each( String^ s in keyColl )
{
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.
*/
// 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.");
}
// 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.
Dictionary<string, string>.ValueCollection valueColl =
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 valueColl )
{
Console.WriteLine("Value = {0}", s);
}
// To get the keys alone, use the Keys property.
Dictionary<string, string>.KeyCollection keyColl =
openWith.Keys;
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
Console.WriteLine();
foreach( string s in keyColl )
{
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.
*/
// Create a new dictionary of strings, with string keys.
let openWith = 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")
with :? ArgumentException ->
printfn "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.
printfn $"""For key = "rtf", value = {openWith["rtf"]}"""
// The indexer can be used to change the value associated
// with a key.
openWith["rtf"] <- "winword.exe"
printfn $"""For key = "rtf", value = {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
printfn $"""For key = "tif", value = {openWith["tif"]}"""
with :? KeyNotFoundException ->
printfn "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.
match openWith.TryGetValue "tif" with
| true, value -> printfn $"For key = \"tif\", value = {value}."
| _ -> printfn "Key = \"tif\" is not found."
// ContainsKey can be used to test keys before inserting
// them.
if openWith.ContainsKey "ht" |> not then
openWith.Add("ht", "hypertrm.exe")
printfn $"""Value added for key = "ht": {openWith["ht"]}"""
// When you use foreach to enumerate dictionary elements,
// the elements are retrieved as KeyValuePair objects.
printfn ""
for kvp in openWith do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
// To get the values alone, use the Values property.
let valueColl = openWith.Values
// The elements of the ValueCollection are strongly typed
// with the type that was specified for dictionary values.
printfn ""
for s in valueColl do
printfn $"Value = {s}"
// To get the keys alone, use the Keys property.
let keyColl = openWith.Keys
// The elements of the KeyCollection are strongly typed
// with the type that was specified for dictionary keys.
printfn ""
for s in keyColl do
printfn $"Key = {s}"
// Use the Remove method to remove a key/value pair.
printfn "\nRemove(\"doc\")"
openWith.Remove "doc" |> ignore
if openWith.ContainsKey "doc" |> not then
printfn "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.
'
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 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 valueColl As _
Dictionary(Of String, String).ValueCollection = _
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 valueColl
Console.WriteLine("Value = {0}", s)
Next s
' To get the keys alone, use the Keys property.
Dim keyColl As _
Dictionary(Of String, String).KeyCollection = _
openWith.Keys
' The elements of the KeyCollection are strongly typed
' with the type that was specified for dictionary keys.
Console.WriteLine()
For Each s As String In keyColl
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.
'
備註
Dictionary<TKey,TValue> 泛型類別提供從一組索引鍵到一組值的對應。 字典的每個新增專案都包含一個值及其相關聯的索引鍵。 使用索引鍵擷取值的速度非常快,接近 O(1),因為 Dictionary<TKey,TValue> 類別會實作為哈希表。
注意
擷取的速度取決於針對 TKey
所指定型別的哈希演演算法品質。
只要對象當做 Dictionary<TKey,TValue>中的索引鍵使用,就不得以任何影響其哈希值的方式變更。 根據字典的相等比較子,Dictionary<TKey,TValue> 中的每個索引鍵都必須是唯一的。 索引鍵不能 null
,但如果索引鍵的類型 TValue
為參考型別,則可以是值。
Dictionary<TKey,TValue> 需要相等實作,才能判斷索引鍵是否相等。 您可以使用接受 comparer
參數的建構函式來指定 IEqualityComparer<T> 泛型介面的實作;如果您未指定實作,則會使用預設的泛型相等比較子 EqualityComparer<T>.Default。 如果類型 TKey
實作 System.IEquatable<T> 泛型介面,則預設相等比較子會使用該實作。
注意
例如,您可以使用 StringComparer 類別所提供的不區分大小寫字串比較子來建立不區分大小寫字串索引鍵的字典。
Dictionary<TKey,TValue> 的容量是 Dictionary<TKey,TValue> 可以保存的項目數目。 當元素新增至 Dictionary<TKey,TValue>時,重新配置內部數位會自動增加容量。
僅限 .NET Framework : 對於非常大的 Dictionary<TKey,TValue> 物件,您可以將運行時間環境中 <gcAllowVeryLargeObjects>
組態 true
專案的 enabled
屬性,將 64 位系統上的最大容量增加到 20 億個元素。
為了列舉的目的,字典中的每個專案都會被視為代表值及其索引鍵的 KeyValuePair<TKey,TValue> 結構。 傳回項目的順序未定義。
C# 語言的 foreach
語句 (for each
在 C++ 中,在 Visual Basic 中 For Each
) 會傳回集合中專案類型的 物件。 由於 Dictionary<TKey,TValue> 是索引鍵和值的集合,因此元素類型不是索引鍵的類型或值的型別。 相反地,元素類型是索引鍵類型和實值類型的 KeyValuePair<TKey,TValue>。 例如:
for each(KeyValuePair<String^, String^> kvp in myDictionary)
{
Console::WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
foreach( KeyValuePair<string, string> kvp in myDictionary )
{
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value);
}
for kvp in myDictionary do
printfn $"Key = {kvp.Key}, Value = {kvp.Value}"
For Each kvp As KeyValuePair(Of String, String) In myDictionary
Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value)
Next kvp
foreach
語句是列舉值周圍的包裝函式,它只允許從集合讀取,而不是寫入集合。
注意
因為索引鍵可以繼承並變更其行為,所以使用 Equals 方法的比較無法保證其絕對唯一性。
建構函式
屬性
Capacity |
取得內部數據結構可以保留而不重設大小的元素總數。 |
Comparer |
取得用來判斷字典索引鍵相等的 IEqualityComparer<T>。 |
Count |
取得包含在 Dictionary<TKey,TValue>中的索引鍵/值組數目。 |
Item[TKey] |
取得或設定與指定索引鍵相關聯的值。 |
Keys |
取得集合,其中包含 Dictionary<TKey,TValue>中的索引鍵。 |
Values |
取得集合,其中包含 Dictionary<TKey,TValue>中的值。 |
方法
Add(TKey, TValue) |
將指定的索引鍵和值加入至字典。 |
Clear() |
從 Dictionary<TKey,TValue>移除所有索引鍵和值。 |
ContainsKey(TKey) |
判斷 Dictionary<TKey,TValue> 是否包含指定的索引鍵。 |
ContainsValue(TValue) |
判斷 Dictionary<TKey,TValue> 是否包含特定值。 |
EnsureCapacity(Int32) |
確保字典最多可以保留一些指定的專案,而不會進一步擴充其備份記憶體。 |
Equals(Object) |
判斷指定的物件是否等於目前的物件。 (繼承來源 Object) |
GetEnumerator() |
傳回逐一查看 Dictionary<TKey,TValue>的列舉值。 |
GetHashCode() |
做為預設哈希函式。 (繼承來源 Object) |
GetObjectData(SerializationInfo, StreamingContext) |
已淘汰.
實作 ISerializable 介面,並傳回串行化 Dictionary<TKey,TValue> 實例所需的數據。 |
GetType() |
取得目前實例的 Type。 (繼承來源 Object) |
MemberwiseClone() |
建立目前 Object的淺層複本。 (繼承來源 Object) |
OnDeserialization(Object) |
實作 ISerializable 介面,並在還原串行化完成時引發還原串行化事件。 |
Remove(TKey) |
從 Dictionary<TKey,TValue>移除具有指定索引鍵的值。 |
Remove(TKey, TValue) |
從 Dictionary<TKey,TValue>中移除具有指定索引鍵的值,並將專案複製到 |
ToString() |
傳回表示目前 物件的字串。 (繼承來源 Object) |
TrimExcess() |
將此字典的容量設定為原本已使用其所有專案初始化的容量。 |
TrimExcess(Int32) |
設定此字典的容量,以保留指定的項目數目,而不會進一步擴充其備份記憶體。 |
TryAdd(TKey, TValue) |
嘗試將指定的索引鍵和值新增至字典。 |
TryGetValue(TKey, TValue) |
取得與指定索引鍵相關聯的值。 |
明確介面實作
擴充方法
適用於
執行緒安全性
只要集合未修改,Dictionary<TKey,TValue> 就可以同時支援多個讀取器。 即便如此,透過集合列舉本質上不是安全線程的程式。 在列舉與寫入存取權競爭的罕見情況下,整個列舉期間必須鎖定集合。 若要允許多個線程存取集合以進行讀取和寫入,您必須實作自己的同步處理。
如需安全線程的替代方案,請參閱 ConcurrentDictionary<TKey,TValue> 類別或 ImmutableDictionary<TKey,TValue> 類別。
此類型的公用靜態 (Shared
) 成員是安全線程。