c# - String.Equals vs String.Compare vs "=="实战。需要解释

标签 c# .net string string-comparison

以下是来自控制台应用程序的代码片段 -

class MyClass
{        
   public int GetDay(string data22)
    {
        int returnValue = 0;

        if (string.Compare(data22,"THURSDAY") == 0) // true
        {
            returnValue = (int)DayOfWeek.Thursday;
        }

        if (data22 == "THURSDAY") //false
        {
            returnValue = (int)DayOfWeek.Thursday;
        }

        if (string.Equals(data22, "THURSDAY"))//false
        {
            returnValue = (int)DayOfWeek.Thursday;
        }
        return returnValue;
    }
}

class Program
{
    static void Main(string[] args)
    {
        string ExecutionDay = "‎THURSDAY";
        MyClass obj1 = new MyClass();
        int MyDays = obj1.GetDay(ExecutionDay);
    }
}

问题是 - 为什么第一个比较 (string.compare) 有效而其他两种比较方法在这个特殊情况下不起作用?

最佳答案

Why does the first comparison (string.compare) work and the other two comparison methods does not work in THIS PARTICULAR CASE

您的代码中存在不可见字符(特别是 Left-to-Right mark(感谢@MatthewWatson))。您可以使用任何十六进制编辑器查看它们:

enter image description here

这被 string.Compare 忽略了,而 string.Equals 却没有。你可以在 the docs 中看到它:

Notes to Callers:

Character sets include ignorable characters. The Compare(String, String) method does not consider such characters when it performs a culture-sensitive comparison. For example, if the following code is run on the .NET Framework 4 or later, a culture-sensitive comparison of "animal" with "ani-mal" (using a soft hyphen, or U+00AD) indicates that the two strings are equivalent.

关于c# - String.Equals vs String.Compare vs "=="实战。需要解释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30885034/

相关文章:

c# - 如何将此 VB.net/C# 代码移植到 Objective-C/iOS?

c# - 对于我在 visual Studio 2013 中的类库项目;使用构建后事件如何将创建的 dll 复制到另一个路径?

.net - 预发布 Collections.Immutable

swift - 如何将存储在变量中的字符串快速转换为可执行代码文本?

ios - 可选原始类型的字符串初始值设定项 : Int? Double?漂浮? ETC

c# - DTO 形状 : flat, 复杂/嵌套,或两者的混合

c# - 如何使面板控件显示在所有其他控件下方?

c# - 如何使用 RadioButton 使其他 RadioButton 可见?

c# - WPF 中的进度条样式是过时的。酒吧的增量。如何实现带有vista或windows-7 shady glow效果的进度条?

c++ - C++中的字符串分配 : why does this work?