我应该超载==运算符吗? [英] Should I Overload == Operator?

查看:123
本文介绍了我应该超载==运算符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

==运算符在C#中如何真正起作用?如果用于比较 A 类的对象,它将尝试匹配所有 A 的属性,还是会寻找指向相同内存位置的指针(或者也许是其他)?

How does the == operator really function in C#? If it used to compare objects of class A, will it try to match all of A's properties, or will it look for pointers to the same memory location (or maybe something else)?

让我们创建一个假设的例子.我正在编写一个使用Twitter API的应用程序,它有一个 Tweet 类,该类具有单个tweet的所有属性:文本,发件人,日期和时间,来源等.如果我想要比较类 Tweet 的对象的等效性,我可以使用:

Let's create a hypothetical example. I'm writing an application that utilizes the Twitter API, and it has a Tweet class, which has all the properties of a single tweet: text, sender, date&time, source, etc. If I want to compare objects of class Tweet for equivalence, can I just use:

Tweet a, b;
if (a == b)
{
//do something...
}

是否会检查在 a b 之间的 Tweet 类的所有属性的等效性?

Will that check for equivalence of all the properties of the Tweet class between a and b?

如果不是,正确的方法是重载==运算符以显式检查所有字段的等效性吗?

If not, would the correct approach be to overload the == operator to explicitly check for equivalence of all the fields?

更新:从前两个答案中我可以正确地假设:

UPDATE: From the first two answers, am I right in assuming:

  • 如果某个类的==运算符或 Equals 方法没有重载,则使用 object 类的==运算符.
  • object 类的==运算符检查内存位置是否相等.
  • 我必须重载==运算符或 Equals 方法才能完成此任务.
  • 在重载中,我必须手动检查属性是否相等,因此无法半自动地(例如,循环执行),对吗?
  • If the == operator or Equals method is not overloaded for a class, the == operator for the object class is used.
  • The == operator for the object class checks for equality in memory location.
  • I have to overload the == operator or the Equals method to accomplish this task.
  • In the overload, I have to check for equivalence in properties manually, so there is no way to do it semi-automatically, say, in a loop, right?

更新#2: Yuriy评论说,可以通过 reflecting 来检查==运算符中属性的等效性.如何才能做到这一点?您能给我一些示例代码吗?谢谢!

UPDATE #2: Yuriy made a comment that it is possible to do check for equivalence in properties in the == operator with reflection. How can this be done? Could you give me some sample code? Thanks!

推荐答案

MSDN具有良好的

MSDN has a good example of how to do it:

   public override bool Equals(object o) 
   {
      try 
      {
         return (bool) (this == (DBBool) o);
      }
      catch 
      {
         return false;
      }
   }

然后重载==和!=:

// Equality operator. Returns dbNull if either operand is dbNull, 
   // otherwise returns dbTrue or dbFalse:
   public static DBBool operator ==(DBBool x, DBBool y) 
   {
      if (x.value == 0 || y.value == 0) return dbNull;
      return x.value == y.value? dbTrue: dbFalse;
   }

   // Inequality operator. Returns dbNull if either operand is
   // dbNull, otherwise returns dbTrue or dbFalse:
   public static DBBool operator !=(DBBool x, DBBool y) 
   {
      if (x.value == 0 || y.value == 0) return dbNull;
      return x.value != y.value? dbTrue: dbFalse;
   }

别忘了重载GetHash方法.

And don't forget to overload the GetHash method.

我编写了以下快速示例,用于在比较中使用反射.这将必须更加全面,如果人们希望我这样做,我可以尝试在其上写一个博客:

I wrote the following quick sample for using reflection in a compare. This would have to be much more comprehensive, I might try doing a blog on it if people want me to:

public class TestEquals
{
    private int _x;
    public TestEquals(int x)
    {
        this._x = x;
    }

    public override bool Equals(object obj)
    {
        TestEquals te = (TestEquals)obj;
        if (te == null) return false;

        foreach (var field in typeof(TestEquals)
            .GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
        {
            if (!field.GetValue(this).Equals(field.GetValue(te)))
                return false;
        }
        return true;
    }
}

这篇关于我应该超载==运算符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆