以下是来自控制台应用程序的代码片段 -
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))。您可以使用任何十六进制编辑器查看它们:
这被 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/