C# 类型比较:Type.Equals 与运算符 == [英] C# Type Comparison: Type.Equals vs operator ==

查看:26
本文介绍了C# 类型比较:Type.Equals 与运算符 ==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ReSharper 建议更改以下内容:

ReSharper suggests that the following be changed from:

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,而 == 将检查类型本身.

I suggest that you read the excellent When is a Type not a Type? blog post by Brad Wilson. To summarize: a runtime type (represented by the internal type RuntimeType), managed by the CLR, is not always the same as a Type, which can be extended. Equals will check the underlying system type, whereas == will check the type itself.

一个简单的例子:

Type type = new TypeDelegator(typeof(int));
Console.WriteLine(type.Equals(typeof(int))); // Prints True
Console.WriteLine(type == typeof(int));      // Prints False

这篇关于C# 类型比较:Type.Equals 与运算符 ==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆