📌  相关文章
📜  C#|检查HybridDictionary中的特定密钥

📅  最后修改于: 2021-05-29 23:50:04             🧑  作者: Mango

HybridDictionary.Contains(Object)方法用于确定HybridDictionary是否包含特定键。

句法:

public bool Contains (object key);

在这里,是要在HybridDictionary中定位的键。

返回值:如果HybridDictionary包含具有指定键的条目,则此方法将返回True ,否则返回False

异常:如果键为null,则该方法将引发ArgumentNullException

下面的程序说明了HybridDictionary.Contains(Object)方法的用法:

范例1:

// C# code to check whether the
// HybridDictionary contains a specific key.
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HybridDictionary named myDict
        HybridDictionary myDict = new HybridDictionary();
  
        // Adding key/value pairs in myDict
        myDict.Add("A", "Apple");
        myDict.Add("B", "Banana");
        myDict.Add("C", "Cat");
        myDict.Add("D", "Dog");
        myDict.Add("E", "Elephant");
        myDict.Add("F", "Fish");
  
        // To check whether the HybridDictionary
        // contains "G".
        Console.WriteLine(myDict.Contains("G"));
  
        // To check whether the HybridDictionary
        // contains "B".
        Console.WriteLine(myDict.Contains("B"));
    }
}

输出:

False
True

范例2:

// C# code to check whether the
// HybridDictionary contains a specific key.
using System;
using System.Collections;
using System.Collections.Specialized;
  
class GFG {
  
    // Driver code
    public static void Main()
    {
  
        // Creating a HybridDictionary named myDict
        HybridDictionary myDict = new HybridDictionary();
  
        // Adding key/value pairs in myDict
        myDict.Add("I", "first");
        myDict.Add("II", "second");
        myDict.Add("III", "third");
        myDict.Add("IV", "fourth");
        myDict.Add("V", "fifth");
  
        // To check whether the HybridDictionary
        // contains "null". This should raise
        // "ArgumentNullException" as key is null
        Console.WriteLine(myDict.Contains(null));
    }
}

运行时错误:

注意:此方法是O(1)操作。

参考:

  • https://docs.microsoft.com/zh-cn/dotnet/api/system.collections.specialized.hybriddictionary.contains?view=netframework-4.7.2