【问题标题】:C# Type Comparison: Type.Equals vs operator ==C# 类型比较:Type.Equals vs operator ==
【发布时间】:2012-03-03 06:57:34
【问题描述】:

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 )

【问题讨论】:

    标签: c# types comparison-operators


    【解决方案1】:

    原因很简单:在这种情况下两者在功能上是等价的,而后者更具可读性。

    【讨论】:

    • R# 通常会提出建议并提供正当理由;在这种情况下,如果它们在功能上是等效的,我怀疑这个建议是为了可读性,这是主观的。我想知道是否还有其他原因被建议?
    • @MetroSmurf - R# 经常为了可读性而提出建议(例如,减少 if 语句中的嵌套)。
    • 这很可能是预期的原因,但由于在这种情况下两者在功能上并不等同,那么这肯定是 Resharper 中的错误吗?
    【解决方案2】:

    来自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 提供,并使用反射进行比较, 这使得它比特定类型慢得多 执行通常会。此实现还调用 在被比较的两个值内的成对引用上相等。

    但是,两种比较类型的主要区别在于 正常使用(您不太可能定义自己的值类型 经常)是多态性。运算符被重载,而不是被覆盖, 这意味着除非编译器知道调用更具体的 版本,它只会调用身份版本。

    【讨论】:

    • 这个答案没有告诉我们Type 类的实例如何定义Equals==。所以我看不出这是对这个问题的有用答案。这个答案是否基于误读问题?
    【解决方案3】:

    我建议您阅读 Brad Wilson 出色的 When is a Type not a Type? 博客文章。总结一下:由 CLR 管理的运行时类型(由内部类型 RuntimeType 表示)并不总是与可以扩展的Type 相同。 Equals 将检查underlying system type,而== 将检查类型本身。

    一个简单的例子:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-26
      • 2019-09-28
      • 2010-10-17
      • 1970-01-01
      相关资源
      最近更新 更多