我不明白为什么 Resharper 建议我在这段代码中“改为检查引用相等性”:
if ( typeToTranslate.Equals( typeof(string) ) )
{
//do something
}
为什么这应该更好:
typeToTranslate == typeof(string)
------------编辑------------
这是方法 stub :
protected IType TranslateType(Type typeToTranslate)
{
if (typeToTranslate == null) throw new ArgumentNullException("typeToTranslate");
//do some stuff
if (typeToTranslate.Equals(typeof(string)))
{
//do some stuff
}
//return some stuff
}
最佳答案
Object.Equals
是一种比引用相等更通用的相等:if x == y
then x.Equals(y)
,但反过来不一定成立。但是,如 MSDN Library 中所述:
A Type object that represents a type is unique; that is, two Type object references refer to the same object if and only if they represent the same type. This allows for comparison of Type objects using reference equality.
因为 ReSharper 将“检查引用相等性代替”检查选项归类在“通用实践和代码改进”下,我的猜测是 ReSharper 让您知道它足以使用引用相等性进行比较类型;您不需要 Equals
方法隐含的更一般类型的相等性(即使对于类型,两者是等价的)。
关于c# - Resharper 建议 : check for reference equality instead,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13647808/