使用String.Equals(str1,str2)和str1 == str2之间的区别是什么

时间:2011-01-06 22:36:32

标签: c# string equals

  

可能重复:
  C# difference between == and .Equals()

在我的日常代码例程中,我经常使用它们,但实际上并不知道它们彼此之间有多么不同。

if(String.Equals(str1, str2))

if(str1 == str2)

2 个答案:

答案 0 :(得分:6)

(UPDATE)

它们实际上是完全一样的。

public static bool operator ==(string a, string b)
{
    return Equals(a, b);
}

因此==会调用Equals


public static bool Equals(string a, string b)
{
    return ((a == b) || (((a != null) && (b != null)) && EqualsHelper(a, b)));
}

EqualsHelper是一种不安全的方法:

<强>更新 它做什么,它使用整数指针循环遍历字符并将它们作为整数进行比较(一次4byte)。它一次完成10个,然后一个一个。

private static unsafe bool EqualsHelper(string strA, string strB)
{
    int length = strA.Length;
    if (length != strB.Length)
    {
        return false;
    }
    fixed (char* chRef = &strA.m_firstChar)
    {
        fixed (char* chRef2 = &strB.m_firstChar)
        {
            char* chPtr = chRef;
            char* chPtr2 = chRef2;
            while (length >= 10)
            {
                if ((((*(((int*) chPtr)) != *(((int*) chPtr2))) || (*(((int*) (chPtr + 2))) != *(((int*) (chPtr2 + 2))))) || ((*(((int*) (chPtr + 4))) != *(((int*) (chPtr2 + 4)))) || (*(((int*) (chPtr + 6))) != *(((int*) (chPtr2 + 6)))))) || (*(((int*) (chPtr + 8))) != *(((int*) (chPtr2 + 8)))))
                {
                    break;
                }
                chPtr += 10;
                chPtr2 += 10;
                length -= 10;
            }
            while (length > 0)
            {
                if (*(((int*) chPtr)) != *(((int*) chPtr2)))
                {
                    break;
                }
                chPtr += 2;
                chPtr2 += 2;
                length -= 2;
            }
            return (length <= 0);
        }
    }
}

答案 1 :(得分:2)

他们完全一样。以下是ildasm为==

显示的内容
  IL_0002:  call       bool System.String::Equals(string,
                                              string)

另请阅读文档: http://msdn.microsoft.com/en-us/library/system.string.op_equality.aspx 它说

  

此运算符使用Equals方法

实现
相关问题