StringDictionary.ContainsKey(String)方法用于检查StringDictionary是否包含特定键。
句法:
public virtual bool ContainsKey (string key);
在这里, key是要在StringDictionary中定位的键。
返回值:如果StringDictionary包含具有指定键的条目,则此方法返回true ,否则返回false 。
异常:如果键为null,则此方法将提供ArgumentNullException 。
下面的程序说明了StringDictionary.ContainsKey(String)方法的用法:
范例1:
// C# code to check if the
// StringDictionary contains
// a specific key
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("G", "Geeks");
myDict.Add("F", "For");
myDict.Add("C", "C++");
myDict.Add("DS", "Data Structures");
myDict.Add("N", "Noida");
// Checking if "DS" is contained in
// StringDictionary myDict
if (myDict.ContainsKey("DS"))
Console.WriteLine("StringDictionary myDict contains the key");
else
Console.WriteLine("StringDictionary myDict does not contain the key");
}
}
输出:
StringDictionary myDict contains the key
范例2:
// C# code to check if the
// StringDictionary contains
// a specific key
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("G", "Geeks");
myDict.Add("F", "For");
myDict.Add("C", "C++");
myDict.Add("DS", "Data Structures");
myDict.Add("N", "Noida");
// Checking if "null" is contained in
// StringDictionary myDict
// This should raise "ArgumentNullException"
// as the key is null
if (myDict.ContainsKey(null))
Console.WriteLine("StringDictionary myDict contains the key");
else
Console.WriteLine("StringDictionary myDict does not contain the key");
}
}
运行时错误:
Unhandled Exception:
System.ArgumentNullException: Value cannot be null.
Parameter name: key
笔记:
- 密钥以不区分大小写的方式处理,即在将密钥添加到字符串字典之前将其转换为小写形式。
- 此方法是O(1)操作。
参考:
- https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.stringdictionary.containskey?view=netframework-4.7.2