📜  C#|检查是否有两个HashSet<T>对象相等

📅  最后修改于: 2021-05-29 19:09:37             🧑  作者: Mango

从Object类继承的Equals(Object)方法用于检查指定的HashSet 对象是否等于另一个HashSet 对象。

句法:

public virtual bool Equals (object obj);

此处,obj是要与当前对象进行比较的对象。

返回值:如果指定对象等于当前对象,则此方法返回true ,否则返回false

下面的程序说明了上面讨论的方法的使用:

范例1:

// C# program to if a HashSet object
// is equal to another HashSet object
using System;
using System.Collections.Generic;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a HashSet of strings
        HashSet mySet = new HashSet();
  
        // Inserting elements in HashSet
        mySet.Add("DS");
        mySet.Add("C++");
        mySet.Add("Java");
        mySet.Add("JavaScript");
  
        // Checking whether mySet is
        // equal to itself or not
        Console.WriteLine(mySet.Equals(mySet));
    }
}
输出:
True

范例2:

// C# program to if a HashSet object
// is equal to another HashSet object
using System;
using System.Collections.Generic;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a HashSet of strings
        HashSet mySet1 = new HashSet();
  
        // Inserting elements in HashSet
        mySet1.Add("HTML");
        mySet1.Add("CSS");
        mySet1.Add("PHP");
        mySet1.Add("DBMS");
  
        // Creating a HashSet of integers
        HashSet mySet2 = new HashSet();
  
        // Inserting elements in HashSet
        for (int i = 0; i < 5; i++) {
            mySet2.Add(i * 2);
        }
  
        // Checking whether mySet1 is
        // equal to mySet2 or not
        Console.WriteLine(mySet1.Equals(mySet2));
  
        // Creating a HashSet of integers
        HashSet mySet3 = new HashSet();
  
        // Assigning mySet2 to mySet3
        mySet3 = mySet2;
  
        // Checking whether mySet3 is
        // equal to mySet2 or not
        Console.WriteLine(mySet3.Equals(mySet2));
    }
}
输出:
False
True