C#类型比较:Type.Equals VS运营商== [英] C# Type Comparison: Type.Equals vs operator ==
本文介绍了C#类型比较:Type.Equals VS运营商==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
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 );
问
为什么会运算符==
推荐过等于(O型)
比较类型时?
推荐答案
我建议你阅读优秀的当是一类不是一个类型?博客文章由布拉德·威尔逊。总结:一个运行时类型(再由内部类型RuntimeType psented $ P $),由CLR管理并不总是一样的类型
,它可以延长。 等于
将检查底层系统类型,而 ==
将检查该类型本身。
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 VS运营商==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文