更新:2007 年 11 月
| TypeName | DoNotOverloadOperatorEqualsOnReferenceTypes | 
| CheckId | CA1046 | 
| 类别 | Microsoft.Design | 
| 是否重大更改 | 是 | 
原因
公共或嵌套公共引用类型重载了相等运算符。
规则说明
对于引用类型,相等运算符的默认实现几乎始终是正确的。默认情况下,仅当两个引用指向同一对象时,它们才相等。
如何修复冲突
要修复与该规则的冲突,请移除相等运算符的实现。
何时禁止显示警告
当引用类型的工作方式类似于内置值类型时,可以安全地禁止显示此规则发出的警告。如果对类型的实例进行相加或相减有意义,则实现相等运算符并禁止显示冲突可能是正确的。
示例
下面的示例演示比较两个引用时的默认行为。
using System;
namespace DesignLibrary
{
   public class MyReferenceType
   {
      private int a, b;
      public MyReferenceType (int a, int b)
      {
         this.a = a;
         this.b = b;
      }
      public override string ToString()
      {
         return String.Format("({0},{1})", a, b);
      }
   }
}
下面的应用程序比较一些引用。
using System;
namespace DesignLibrary
{
    public class ReferenceTypeEquality
    {
       public static void Main()
       {
          MyReferenceType a = new MyReferenceType(2,2);
          MyReferenceType b = new MyReferenceType(2,2);
          MyReferenceType c = a;
          Console.WriteLine("a = new {0} and b = new {1} are equal? {2}", a,b, a.Equals(b)? "Yes":"No");
          Console.WriteLine("c and a are equal? {0}", c.Equals(a)? "Yes":"No");
          Console.WriteLine("b and a are == ? {0}", b == a ? "Yes":"No");
          Console.WriteLine("c and a are == ? {0}", c == a ? "Yes":"No");     
       }
    }
}
该示例产生下面的输出。
a = new (2,2) and b = new (2,2) are equal? No
c and a are equal? Yes
b and a are == ? No
c and a are == ? Yes