📜  C#|检查两个ArrayList对象是否相等

📅  最后修改于: 2021-05-30 00:00:55             🧑  作者: Mango

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

句法:

public virtual bool Equals (object obj);

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

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

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

范例1:

// C# program to if a ArrayList
// is equal to itself or not
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a ArrayList
        ArrayList arrlist = new ArrayList();
  
        // Adding elements to ArrayList
        arrlist.Add(1);
        arrlist.Add(2);
        arrlist.Add(3);
        arrlist.Add(4);
        arrlist.Add(5);
  
        // Checking whether arrlistis
        // equal to itself or not
        Console.WriteLine(arrlist.Equals(arrlist));
    }
}
输出:
True

示例2: equals方法仅检查两个ArrayList引用是否都引用同一对象。如果两个对象不同,即使它们具有相同的值,它也会返回false。

// C# program to if a ArrayList
// is equal to another ArrayList
using System;
using System.Collections;
  
class Geeks {
  
    // Main Method
    public static void Main(String[] args)
    {
  
        // Creating a ArrayList
        ArrayList arrlist = new ArrayList();
  
        // Adding elements to ArrayList
        arrlist.Add("This");
        arrlist.Add("is");
        arrlist.Add("C#");
        arrlist.Add("ArrayList");
        arrlist.Add("Tutorial.");
  
        // Creating an ArrayList
        ArrayList arrlist2 = new ArrayList();
  
        // Adding elements to ArrayList
        arrlist2.Add("This");
        arrlist2.Add("is");
        arrlist2.Add("C#");
        arrlist2.Add("ArrayList");
        arrlist2.Add("Tutorial.");
  
        // Checking whether arrlist is
        // equal to arrlist2 or not
        Console.WriteLine(arrlist.Equals(arrlist2));
  
        // Creating a ArrayList
        ArrayList arrlist3 = new ArrayList();
  
        // Assigning arrlist2 to arrlist3
        arrlist3 = arrlist2;
  
        // Checking whether arrlist3 is
        // equal to arrlist2 or not
        Console.WriteLine(arrlist3.Equals(arrlist2));
    }
}
输出:
False
True

注意:如果当前实例是引用类型,则Equals(Object)方法将检查引用是否相等。