Difference between C# and VB.Net string comparison

[亡魂溺海] 提交于 2019-11-28 12:37:40

VB.NET inherited the Option Compare statement from previous versions of Visual Basic. To make that work, all string comparison expressions in VB.NET are translated to a helper function that can find out what the selected Option Compare value was in the specific source code file in which the statement was written.

The Operators.CompareString(string, string, bool) method is that helper function. The last argument is named "TextCompare", the VB.NET compiler automatically passes True if Option Compare Text is in effect, False if Option Compare Binary is in effect.

C# doesn't have anything like that.

Decompiling CompareString gives

public static int CompareString(string Left, string Right, bool TextCompare)
{
  if (Left == Right)
    return 0;
  if (Left == null)
    return Right.Length == 0 ? 0 : -1;
  else if (Right == null)
  {
    return Left.Length == 0 ? 0 : 1;
  }
  else
  {
    int num = !TextCompare 
       ? string.CompareOrdinal(Left, Right) 
       : Utils.GetCultureInfo().CompareInfo
              .Compare(Left, Right, CompareOptions.IgnoreCase 
                                  | CompareOptions.IgnoreKanaType 
                                  | CompareOptions.IgnoreWidth);
    if (num == 0)
      return 0;
    return num > 0 ? 1 : -1;
  }
}

from which can be seen that there's custom logic around null ("Nothing in Visual Basic", as the refrain goes) handling, and more importantly, a mode-switching parameter TextCompare, which takes its value from the Option Compare setting in effect.

Perhaps explicitly using a method on string, rather than a comparison operator, would help you out.

As to the 'why', well, VB (classic) was always culturally a more "do the sensible thing" language, as opposed to the "do exactly what I tell you, nothing more, nothing less" philosophy of the C++ / Win32 world. VB.NET and C# are closer, but still differences like this remain.

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