[英]C# Type Comparison: Type.Equals vs operator ==
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 )
?
我建议你阅读优秀的什么时候类型不是类型? 布拉德威尔逊的博客文章。 总结一下:由 CLR 管理的运行时类型(由内部类型 RuntimeType 表示)并不总是与可以扩展的Type
相同。 Equals
将检查底层系统类型,而==
将检查类型本身。
一个简单的例子:
Type type = new TypeDelegator(typeof(int));
Console.WriteLine(type.Equals(typeof(int))); // Prints True
Console.WriteLine(type == typeof(int)); // Prints False
原因很简单:在这种情况下,两者在功能上是等效的,而后者更具可读性。
Equals 方法只是在 System.Object 中定义的一个虚拟方法,并被任何选择这样做的类覆盖。 == 运算符是一个可以被类重载的运算符,但它通常具有标识行为。
对于 == 没有被重载的引用类型,它比较两个引用是否引用同一个对象——这正是 System.Object 中 Equals 的实现所做的。
默认情况下,值类型不为 == 提供重载。 但是,框架提供的大多数值类型都提供了它们自己的重载。 值类型的 Equals 的默认实现由 ValueType 提供,并使用反射进行比较,这使得它比通常的类型特定实现慢得多。 此实现还对要比较的两个值中的引用对调用 Equals。
但是,在正常使用中(您不太可能经常定义自己的值类型)这两种比较类型之间的主要区别是多态性。 运算符是重载的,而不是被覆盖的,这意味着除非编译器知道调用更具体的版本,否则它只会调用标识版本。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.