[英]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.