43

ReSharper 建议更改以下内容:

Type foo = typeof( Foo );
Type bar = typeof( Bar );

if( foo.Equals( bar ) ) { ... }

至:

if( foo == bar ) { ... }

运算符 ==

// Summary:
//     Indicates whether two System.Type objects are equal.
//
// Parameters:
//   left:
//     The first object to compare.
//
//   right:
//     The second object to compare.
//
// Returns:
//     true if left is equal to right; otherwise, false.
public static bool operator ==( Type left, Type right );

等于(类型 o)

// Summary:
//     Determines if the underlying system type of the current System.Type is the
//     same as the underlying system type of the specified System.Type.
//
// Parameters:
//   o:
//     The System.Type whose underlying system type is to be compared with the underlying
//     system type of the current System.Type.
//
// Returns:
//     true if the underlying system type of o is the same as the underlying system
//     type of the current System.Type; otherwise, false.
public virtual bool Equals( Type o );

问题
为什么在比较类型时会operator ==被推荐?Equals( Type o )

4

3 回答 3

47

我建议你阅读优秀的When is a Type not a Type?布拉德威尔逊的博客文章。总而言之:由 CLR 管理的运行时类型(由内部类型 RuntimeType 表示)并不总是与Type可以扩展的 a 相同。Equals将检查底层系统类型,而==将检查类型本身。

一个简单的例子:

Type type = new TypeDelegator(typeof(int));
Console.WriteLine(type.Equals(typeof(int))); // Prints True
Console.WriteLine(type == typeof(int));      // Prints False
于 2012-02-13T10:56:41.403 回答
2

原因很简单:在这种情况下,两者在功能上是等价的,而后者更具可读性。

于 2012-02-10T19:58:12.620 回答
-2

来自http://blogs.msdn.com/b/csharpfaq/archive/2004/03/29/when-should-i-use-and-when-should-i-use-equals.aspx

Equals 方法只是在 System.Object 中定义的一个虚拟方法,并且被选择这样做的任何类覆盖。== 运算符是一个可以被类重载的运算符,但通常具有标识行为。

对于 == 没有被重载的引用类型,它会比较两个引用是否引用同一个对象——这正是 Equals 在 System.Object 中的实现。

默认情况下,值类型不为 == 提供重载。但是,框架提供的大多数值类型都提供了自己的重载。值类型的 Equals 的默认实现由 ValueType 提供,并使用反射进行比较,这使得它比通常的特定于类型的实现慢得多。此实现还对正在比较的两个值内的引用对调用 Equals。

但是,在正常使用中(您不太可能经常定义自己的值类型)这两种比较类型之间的主要区别是多态性。运算符是重载的,而不是被覆盖的,这意味着除非编译器知道调用更具体的版本,否则它只会调用标识版本。

于 2012-02-10T20:00:25.483 回答