String.Equals vs String.Compare vs"=="在行动中.需要说明 [英] String.Equals vs String.Compare vs "==" in Action. Explanation needed

查看:44
本文介绍了String.Equals vs String.Compare vs"=="在行动中.需要说明的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是控制台应用程序中的代码段-

  class MyClass{public int GetDay(字符串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;}}班级计划{静态void Main(string [] args){字符串ExecutionDay ="THURSDAY";MyClass obj1 =新的MyClass();int MyDays = obj1.GetDay(ExecutionDay);}} 

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

解决方案

为什么第一个比较(string.compare)起作用,而另两个比较比较方法不适用于这种特殊情况

其中包含不可见的字符(尤其是中看到它:

给来电者的提示:

字符集包含可忽略的字符.这Compare(String,String)方法在以下情况下不考虑此类字符它会进行文化敏感的比较.例如,如果以下代码在.NET Framework 4或更高版本上运行,动物"与动物"的文化敏感性比较(使用软连字符或U + 00AD)表示两个字符串是等效的.

Following is the code snippet from a console application -

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);
    }
}

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

解决方案

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

There are invisible characters (particularly, a Left-to-Right mark (Thanks @MatthewWatson)) in your code. You can view them with any hex editor:

This is over-looked by string.Compare, while it isn't with string.Equals. You can see it in 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.

这篇关于String.Equals vs String.Compare vs"=="在行动中.需要说明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆