Resharper suggestion: check for reference equality instead

时光怂恿深爱的人放手 提交于 2019-12-12 10:29:00

问题


I don't understand why Resharper suggest me to "check for reference equality instead" in this code:

if ( typeToTranslate.Equals( typeof(string) ) )
{
    //do something
}

Why this should be better:

typeToTranslate == typeof(string)

------------EDIT------------

This is the method 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
 }

回答1:


Object.Equals is a more general kind of equality than reference equality: if x == y then x.Equals(y), but the converse isn't necessarily true. However, as documented in 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.

Because ReSharper categorizes the "Check for reference equality instead" inspection option under "Common Practices and Code Improvements", my guess is that ReSharper is letting you know that it suffices to use reference equality to compare types; you don't need the more general kind of equality implied by the Equals method (even though for types the two are equivalent).




回答2:


From the System.Type documentation:

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.

This means that "string".GetType() and typeof(string) return the same reference. There is only a single instance of the System.Type object for System.String within an AppDomain.

As to why ReSharper says it's "better" to use == instead of .Equals()? My guess is because == is more efficient and does not risk throwing a NullReferenceException if typeToTranslate were null (in your case).



来源:https://stackoverflow.com/questions/13647808/resharper-suggestion-check-for-reference-equality-instead

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!