C#类型比较:Type.Equals vs运算符==
本文关键字:vs 运算符 Equals Type 类型 比较 | 更新日期: 2023-09-27 18:24:08
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 )
?
我建议您阅读优秀的《当类型不是类型?Brad Wilson的博客文章。总之: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
原因很简单:在这种情况下,两者在功能上是等效的,而后者更可读。
来源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提供,并使用反射进行比较,这使得它比特定类型的要慢得多实现通常是。此实现还调用在被比较的两个值内的引用对上等于。
然而,这两种类型的比较的主要区别在于正常使用(您不太可能定义自己的值类型通常)是多态性。运算符是重载的,而不是重写的,这意味着除非编译器知道调用更具体的版本,它只会调用标识版本。