4
Employee emp1 = new Employee {Name = "Swapnil",Age = 27 };
            Employee emp2 = new Employee { Name = "Swapnil", Age = 27 };
            if (object.Equals(emp1, emp2))
            {

            }
            else
            {
            }

此代码无法比较。我如何在 C# 中比较两个 Object ?

4

3 回答 3

2

在不覆盖 Equals 方法的情况下,只会发生参考比较。您想要执行值比较。

像这样覆盖 Employee 类中的方法:

public override bool Equals(Object emp)
{
    // If parameter is null return false.
    if (emp == null)
    {
        return false;
    }

     // If parameter cannot be cast to Point return false.
    Employee e = emp as Employee;
    if ((System.Object)e == null)
    {
        return false;
    }

    // Return true if the fields match
    return (Name == emp.Name) && (Age == emp.Age);
}

然后像这样比较对象:

if(emp1.Equals(emp2))
{ ... }

或与比较运算符:

if(emp1 == emp2)
{ ... }

更多关于 MSDN 的详细信息:http: //msdn.microsoft.com/en-us/library/ms173147 (v=vs.80).aspx

于 2012-07-27T12:47:14.243 回答
0

您需要覆盖Equals您的Employee课程。示例(从MSDN窃取和修改):

   public override bool Equals(Object obj) 
   {
      // Check for null values and compare run-time types.
      if (obj == null || GetType() != obj.GetType()) 
         return false;

      Employee e = (Employee)obj;
      return (this.Name == e.Name) && (this.Age == e.Age);
   }

然后像这样使用它:

if (emp1.Equals(emp2))
{
    // ...

注意:如果你覆盖Equals(),你也应该覆盖GetHashCode()

于 2012-07-27T12:44:03.463 回答
0

检查链接以获取 Object.Equals 的描述。

如果你离开你的班级,那么所做的比较就是参考比较。这不是您想要的,您想根据您的属性测试是否相等。

如果您在 Employee 类中重写方法 Equals(object),那么您可以在那里实现您的自定义相等测试。请参阅此处,正如 Botz3000 已经给出的,关于如何覆盖此方法并实现自定义测试。

于 2012-07-27T12:50:14.147 回答