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 | |
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) |
获取与指定键关联的值。 |