StringDictionary.Add(String,String)方法用于将具有指定键和值的条目添加到StringDictionary中。
句法:
public virtual void Add (string key, string value);
参数:
- 密钥:这是要添加的条目的密钥。
- value:是要添加的条目的值。该值可以为空。
例外情况:
- ArgumentNullException:如果键为null。
- ArgumentException:这是一个条目,其StringDictionary中已经存在相同的键。
- NotSupportedException:如果StringDictionary是只读的。
下面的程序说明了StringDictionary.Add(String,String)方法的用法:
范例1:
// C# code to add key and value
// into the StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver code
public static void Main()
{
// Creating a StringDictionary named myDict
StringDictionary myDict = new StringDictionary();
// Adding key and value into the StringDictionary
myDict.Add("A", "Apple");
myDict.Add("B", "Banana");
myDict.Add("C", "Cat");
myDict.Add("D", "Dog");
myDict.Add("E", "Elephant");
// Displaying the keys and values in StringDictionary
foreach(DictionaryEntry dic in myDict)
{
Console.WriteLine(dic.Key + " " + dic.Value);
}
}
}
输出:
d Dog
b Banana
c Cat
e Elephant
a Apple
范例2:
// C# code to add key and value
// into the StringDictionary
using System;
using System.Collections;
using System.Collections.Specialized;
class GFG {
// Driver code
public static void Main()
{
// Creating a StringDictionary named myDict
StringDictionary myDict = new StringDictionary();
// Adding key and value into the StringDictionary
myDict.Add("A", "Apple");
myDict.Add("B", "Banana");
myDict.Add("C", "Cat");
myDict.Add("D", "Dog");
// It should raise "ArgumentException"
// as an entry with the same key
// already exists in the StringDictionary.
myDict.Add("C", "Code");
// Displaying the keys and values in StringDictionary
foreach(DictionaryEntry dic in myDict)
{
Console.WriteLine(dic.Key + " " + dic.Value);
}
}
}
运行时错误:
Unhandled Exception:
System.ArgumentException: Item has already been added. Key in dictionary: ‘c’ Key being added: ‘c’
笔记:
- 密钥以不区分大小写的方式处理,即在将密钥添加到字符串字典之前将其转换为小写形式。
- 此方法是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.stringdictionary.add?view=netframework-4.7.2