c# - Resharper 建议 : check for reference equality instead

标签 c# resharper equality

我不明白为什么 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/

相关文章:

c# - C# 中的有效存储库 - 将方法放在哪里?

c# - Unity3D : Find Raycasthit direction

c# - ReSharper 在 "else"上自动插入大括号

c# - Sonar+ReSharper 项目包含链接文件

c# - 测试委托(delegate)是否平等

c# - 如何在我的 C# 应用程序中创建我自己的事件,就像可用的默认事件一样?

c# - 有没有办法将 EF.Functions.Like 与 ESCAPE sql 关键字一起使用来防止通配符

asp.net-mvc - Resharper导航到MVC View

c# - 有没有办法分解 Expression<Func<T, Bool>> 并获得相等比较的右侧?

clojure - 是否期望 identity 返回与其参数不同的东西?