温馨提示×

c# compare案例展示

c#
小樊
83
2024-09-19 19:43:27
栏目: 编程语言

在C#中,比较两个对象是否相等可以通过多种方式进行。以下是一个简单的案例,展示了如何使用==运算符和Equals()方法来比较两个自定义对象。

首先,我们创建一个名为Person的类:

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }

    public Person(string firstName, string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }

    // 重写Equals方法
    public override bool Equals(object obj)
    {
        if (obj == null || obj.GetType() != this.GetType())
        {
            return false;
        }

        Person other = (Person)obj;
        return string.Equals(FirstName, other.FirstName, StringComparison.OrdinalIgnoreCase) &&
               string.Equals(LastName, other.LastName, StringComparison.OrdinalIgnoreCase);
    }

    // 重写GetHashCode方法
    public override int GetHashCode()
    {
        return FirstName.ToLowerInvariant().GetHashCode() ^ LastName.ToLowerInvariant().GetHashCode();
    }
}

在这个类中,我们重写了Equals()方法,以便根据FirstNameLastName属性比较两个Person对象是否相等。我们还重写了GetHashCode()方法,以确保当两个对象相等时,它们具有相同的哈希码。

接下来,我们创建两个Person对象并使用==运算符和Equals()方法进行比较:

class Program
{
    static void Main(string[] args)
    {
        Person person1 = new Person("John", "Doe");
        Person person2 = new Person("John", "Doe");
        Person person3 = new Person("Jane", "Doe");

        // 使用==运算符比较
        bool isEqualUsingOperator = (person1 == person2); // 输出:True
        Console.WriteLine("Is person1 equal to person2 using '==' operator? " + isEqualUsingOperator);

        bool isEqualUsingEqualsMethod = person1.Equals(person2); // 输出:True
        Console.WriteLine("Is person1 equal to person2 using 'Equals()' method? " + isEqualUsingEqualsMethod);

        bool isEqualUsingOperatorWithNull = (person1 == null); // 输出:False
        Console.WriteLine("Is person1 equal to null using '==' operator? " + isEqualUsingOperatorWithNull);

        bool isEqualUsingEqualsMethodWithNull = person1.Equals(null); // 输出:False
        Console.WriteLine("Is person1 equal to null using 'Equals()' method? " + isEqualUsingEqualsMethodWithNull);

        bool isEqualUsingOperatorWithDifferentType = (person1 == person3); // 输出:False
        Console.WriteLine("Is person1 equal to person3 using '==' operator? " + isEqualUsingOperatorWithDifferentType);

        bool isEqualUsingEqualsMethodWithDifferentType = person1.Equals(person3); // 输出:False
        Console.WriteLine("Is person1 equal to person3 using 'Equals()' method? " + isEqualUsingEqualsMethodWithDifferentType);
    }
}

在这个示例中,我们展示了如何使用==运算符和Equals()方法来比较两个Person对象。我们还展示了如何比较一个对象与null以及比较两个不同类型的对象。

0