Met*_*urf 40 c# types comparison-operators
Resharper建议改变以下内容:
Type foo = typeof( Foo );
Type bar = typeof( Bar );
if( foo.Equals( bar ) ) { ... }
Run Code Online (Sandbox Code Playgroud)
至:
if( foo == bar ) { ... }
Run Code Online (Sandbox Code Playgroud)
operator ==
// 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 );
Run Code Online (Sandbox Code Playgroud)
等于(类型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 );
Run Code Online (Sandbox Code Playgroud)
问题
为什么在比较类型时会operator ==被推荐Equals( Type o )?
Jul*_*ain 38
我建议你读一个优秀的类型不是什么类型?Brad Wilson的博客文章.总结一下:由CLR管理的运行时类型(由内部类型RuntimeType表示)并不总是与a相同Type,可以对其进行扩展.Equals将检查基础系统类型,而==将检查类型本身.
一个简单的例子:
Type type = new TypeDelegator(typeof(int));
Console.WriteLine(type.Equals(typeof(int))); // Prints True
Console.WriteLine(type == typeof(int)); // Prints False
Run Code Online (Sandbox Code Playgroud)