Dictionary<TKey,TValue>.IDictionary.Add(Object, Object) メソッド
定義
重要
一部の情報は、リリース前に大きく変更される可能性があるプレリリースされた製品に関するものです。 Microsoft は、ここに記載されている情報について、明示または黙示を問わず、一切保証しません。
指定したキーと値をディクショナリに追加します。
virtual void System.Collections.IDictionary.Add(System::Object ^ key, System::Object ^ value) = System::Collections::IDictionary::Add;
void IDictionary.Add(object key, object value);
abstract member System.Collections.IDictionary.Add : obj * obj -> unit
override this.System.Collections.IDictionary.Add : obj * obj -> unit
Sub Add (key As Object, value As Object) Implements IDictionary.Add
パラメーター
- key
- Object
キーとして使用するオブジェクト。
- value
- Object
値として使用するオブジェクト。
実装
例外
key は nullです。
keyは、Dictionary<TKey,TValue>のキー型TKeyに割り当てられない型です。
-または-
value は、 TValueに割り当てられない型で、 Dictionary<TKey,TValue>内の値の型です。
-または-
同じキーを持つ値が既に Dictionary<TKey,TValue>に存在します。
例
次のコード例は、System.Collections.IDictionary インターフェイスを介して Dictionary<TKey,TValue> クラスにアクセスする方法を示しています。 このコード例では、文字列キーを含む文字列の空の Dictionary<TKey,TValue> を作成し、 IDictionary.Add メソッドを使用していくつかの要素を追加します。 この例では、重複するキーを追加しようとしたとき、または間違ったデータ型のキーまたは値が指定されたときに、 IDictionary.Add メソッドが ArgumentException をスローすることを示します。
このコード例では、 System.Collections.IDictionary インターフェイスの他のいくつかのメンバーを使用する方法を示します。
using System;
using System.Collections;
using System.Collections.Generic;
public class Example
{
public static void Main()
{
// Create a new dictionary of strings, with string keys,
// and access it using the IDictionary interface.
//
IDictionary openWith = new Dictionary<string, string>();
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
// IDictionary.Add throws an exception if incorrect types
// are supplied for key or value.
openWith.Add("txt", "notepad.exe");
openWith.Add("bmp", "paint.exe");
openWith.Add("dib", "paint.exe");
openWith.Add("rtf", "wordpad.exe");
try
{
openWith.Add(42, new Example());
}
catch (ArgumentException ex)
{
Console.WriteLine("An exception was caught for " +
"IDictionary.Add. Exception message:\n\t{0}\n",
ex.Message);
}
// 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 returns null if the key is of the wrong data
// type.
Console.WriteLine("The indexer returns null"
+ " if the key is of the wrong type:");
Console.WriteLine("For key = 2, value = {0}.",
openWith[2]);
// The indexer throws an exception when setting a value
// if the key is of the wrong data type.
try
{
openWith[2] = "This does not get added.";
}
catch (ArgumentException)
{
Console.WriteLine("A key of the wrong type was specified"
+ " when assigning to the indexer.");
}
// Unlike the default Item property on the Dictionary class
// itself, IDictionary.Item does not throw an exception
// if the requested key is not in the dictionary.
Console.WriteLine("For key = \"tif\", value = {0}.",
openWith["tif"]);
// Contains can be used to test keys before inserting
// them.
if (!openWith.Contains("ht"))
{
openWith.Add("ht", "hypertrm.exe");
Console.WriteLine("Value added for key = \"ht\": {0}",
openWith["ht"]);
}
// IDictionary.Contains returns false if the wrong data
// type is supplied.
Console.WriteLine("openWith.Contains(29.7) returns {0}",
openWith.Contains(29.7));
// When you use foreach to enumerate dictionary elements
// with the IDictionary interface, the elements are retrieved
// as DictionaryEntry objects instead of KeyValuePair objects.
Console.WriteLine();
foreach( DictionaryEntry de in openWith )
{
Console.WriteLine("Key = {0}, Value = {1}",
de.Key, de.Value);
}
// To get the values alone, use the Values property.
ICollection icoll = openWith.Values;
// The elements of the collection are strongly typed
// with the type that was specified for dictionary values,
// even though the ICollection interface is not strongly
// typed.
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 collection are strongly typed
// with the type that was specified for dictionary keys,
// even though the ICollection interface is not strongly
// typed.
Console.WriteLine();
foreach( string s in icoll )
{
Console.WriteLine("Key = {0}", s);
}
// Use the Remove method to remove a key/value pair. No
// exception is thrown if the wrong data type is supplied.
Console.WriteLine("\nRemove(\"dib\")");
openWith.Remove("dib");
if (!openWith.Contains("dib"))
{
Console.WriteLine("Key \"dib\" is not found.");
}
}
}
/* This code example produces the following output:
An exception was caught for IDictionary.Add. Exception message:
The value "42" is not of type "System.String" and cannot be used in this generic collection.
Parameter name: key
An element with Key = "txt" already exists.
For key = "rtf", value = wordpad.exe.
For key = "rtf", value = winword.exe.
The indexer returns null if the key is of the wrong type:
For key = 2, value = .
A key of the wrong type was specified when assigning to the indexer.
For key = "tif", value = .
Value added for key = "ht": hypertrm.exe
openWith.Contains(29.7) returns False
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("dib")
Key "dib" is not found.
*/
open System
open System.Collections
open System.Collections.Generic
// Create a new dictionary of strings, with string keys,
// and access it using the IDictionary interface.
let openWith: IDictionary = Dictionary<string, string>()
// Add some elements to the dictionary. There are no
// duplicate keys, but some of the values are duplicates.
// IDictionary.Add throws an exception if incorrect types
// are supplied for key or value.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
type Example() = class end
try
openWith.Add(42, Example())
with :? ArgumentException as ex ->
printfn $"An exception was caught for IDictionary.Add. Exception message:\n\t{ex.Message}\n"
// 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 returns null if the key is of the wrong data
// type.
printfn "The indexer returns null if the key is of the wrong type:"
printfn $"""For key = 2, value = {openWith.[2]}."""
// The indexer throws an exception when setting a value
// if the key is of the wrong data type.
try
openWith[2] <- "This does not get added."
with :? ArgumentException ->
printfn "A key of the wrong type was specified when assigning to the indexer."
// Unlike the default Item property on the Dictionary class
// itself, IDictionary.Item does not throw an exception
// if the requested key is not in the dictionary.
printfn $"""For key = "tif", value = {openWith.["tif"]}."""
// Contains can be used to test keys before inserting
// them.
if openWith.Contains "ht" |> not then
openWith.Add("ht", "hypertrm.exe")
printfn $"""Value added for key = "ht": {openWith["ht"]}"""
// IDictionary.Contains returns false if the wrong data
// type is supplied.
printfn $"openWith.Contains(29.7) returns {openWith.Contains 29.7}"
// When you use foreach to enumerate dictionary elements
// with the IDictionary interface, the elements are retrieved
// as DictionaryEntry objects instead of KeyValuePair objects.
printfn ""
for de in openWith do
let de = de :?> DictionaryEntry
printfn $"For key = {de.Key}, value = {de.Value}"
// To get the values alone, use the Values property.
let icoll: ICollection = openWith.Values
// The elements of the collection are strongly typed
// with the type that was specified for dictionary values,
// even though the ICollection interface is not strongly
// typed.
printfn ""
for s in icoll do
printfn $"Value = {s}"
// To get the keys alone, use the Keys property.
let icoll2: ICollection = openWith.Keys
// The elements of the collection are strongly typed
// with the type that was specified for dictionary keys,
// even though the ICollection interface is not strongly
// typed.
printfn ""
for s in icoll2 do
printfn $"Key = {s}"
// Use the Remove method to remove a key/value pair. No
// exception is thrown if the wrong data type is supplied.
printfn "\nRemove(\"dib\")"
openWith.Remove "dib"
if openWith.Contains "dib" |> not then
printfn "Key \"dib\" is not found."
// This code example produces the following output:
// An exception was caught for IDictionary.Add. Exception message:
// The value "42" is not of type "System.String" and cannot be used in this generic collection.
// Parameter name: key
//
// An element with Key = "txt" already exists.
// For key = "rtf", value = wordpad.exe.
// For key = "rtf", value = winword.exe.
// The indexer returns null if the key is of the wrong type:
// For key = 2, value = .
// A key of the wrong type was specified when assigning to the indexer.
// For key = "tif", value = .
// Value added for key = "ht": hypertrm.exe
// openWith.Contains(29.7) returns False
//
// 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("dib")
// Key "dib" is not found.
Imports System.Collections
Imports System.Collections.Generic
Public Class Example
Public Shared Sub Main()
' Create a new dictionary of strings, with string keys,
' and access it using the IDictionary interface.
'
Dim openWith As IDictionary = _
New Dictionary(Of String, String)
' Add some elements to the dictionary. There are no
' duplicate keys, but some of the values are duplicates.
' IDictionary.Add throws an exception if incorrect types
' are supplied for key or value.
openWith.Add("txt", "notepad.exe")
openWith.Add("bmp", "paint.exe")
openWith.Add("dib", "paint.exe")
openWith.Add("rtf", "wordpad.exe")
Try
openWith.Add(42, New Example())
Catch ex As ArgumentException
Console.WriteLine("An exception was caught for " & _
"IDictionary.Add. Exception message:" & vbLf _
& vbTab & ex.Message & vbLf)
End Try
' 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 returns Nothing if the key
' is of the wrong data type.
Console.WriteLine("The default Item property returns Nothing" _
& " if the key is of the wrong type:")
Console.WriteLine("For key = 2, value = {0}.", _
openWith(2))
' The default Item property throws an exception when setting
' a value if the key is of the wrong data type.
Try
openWith(2) = "This does not get added."
Catch
Console.WriteLine("A key of the wrong type was specified" _
& " when setting the default Item property.")
End Try
' Unlike the default Item property on the Dictionary class
' itself, IDictionary.Item does not throw an exception
' if the requested key is not in the dictionary.
Console.WriteLine("For key = ""tif"", value = {0}.", _
openWith("tif"))
' Contains can be used to test keys before inserting
' them.
If Not openWith.Contains("ht") Then
openWith.Add("ht", "hypertrm.exe")
Console.WriteLine("Value added for key = ""ht"": {0}", _
openWith("ht"))
End If
' IDictionary.Contains returns False if the wrong data
' type is supplied.
Console.WriteLine("openWith.Contains(29.7) returns {0}", _
openWith.Contains(29.7))
' When you use foreach to enumerate dictionary elements
' with the IDictionary interface, the elements are retrieved
' as DictionaryEntry objects instead of KeyValuePair objects.
Console.WriteLine()
For Each de As DictionaryEntry In openWith
Console.WriteLine("Key = {0}, Value = {1}", _
de.Key, de.Value)
Next
' To get the values alone, use the Values property.
Dim icoll As ICollection = openWith.Values
' The elements of the collection are strongly typed
' with the type that was specified for dictionary values,
' even though the ICollection interface is not strongly
' typed.
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 collection are strongly typed
' with the type that was specified for dictionary keys,
' even though the ICollection interface is not strongly
' typed.
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. No
' exception is thrown if the wrong data type is supplied.
Console.WriteLine(vbLf + "Remove(""dib"")")
openWith.Remove("dib")
If Not openWith.Contains("dib") Then
Console.WriteLine("Key ""dib"" is not found.")
End If
End Sub
End Class
' This code example produces the following output:
'
'An exception was caught for IDictionary.Add. Exception message:
' The value "42" is not of type "System.String" and cannot be used in this generic collection.
'Parameter name: key
'
'An element with Key = "txt" already exists.
'For key = "rtf", value = wordpad.exe.
'For key = "rtf", value = winword.exe.
'The default Item property returns Nothing if the key is of the wrong type:
'For key = 2, value = .
'A key of the wrong type was specified when setting the default Item property.
'For key = "tif", value = .
'Value added for key = "ht": hypertrm.exe
'openWith.Contains(29.7) returns False
'
'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("dib")
'Key "dib" is not found.
'
注釈
Item[] プロパティを使用して、ディクショナリに存在しないキーの値 (myCollection["myNonexistentKey"] = myValueなど) を設定して、新しい要素を追加することもできます。 ただし、指定したキーがディクショナリに既に存在する場合は、 Item[] プロパティを設定すると、古い値が上書きされます。 これに対し、 Add メソッドは、指定したキーが既に存在する場合に例外をスローします。
Count容量より小さい場合、このメソッドは O(1) 操作に近づきます。 新しい要素に対応するために容量を増やす必要がある場合、このメソッドは O(n) 操作になり、 n が Countされます。