加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – string.Empty.StartsWith(((char)10781).ToString())总是

发布时间:2020-12-15 18:22:31 所属栏目:百科 来源:网络整理
导读:我试图处理以下角色:?( http://www.fileformat.info/info/unicode/char/2a1d/index.htm) 如果你检查一个以这个字符开头的空字符串,它总是返回true,这没有任何意义!这是为什么? // visual studio 2008 hides lines that have this char literally (bug in
我试图处理以下角色:?( http://www.fileformat.info/info/unicode/char/2a1d/index.htm)

如果你检查一个以这个字符开头的空字符串,它总是返回true,这没有任何意义!这是为什么?

// visual studio 2008 hides lines that have this char literally (bug in visual studio?!?) so i wrote it's unicode instead.
char specialChar = (char)10781;
string specialString = specialChar.ToString();

// prints 1
Console.WriteLine(specialString.Length);

// prints 10781
Console.WriteLine((int)specialChar);

// prints false
Console.WriteLine(string.Empty.StartsWith("A"));

// both prints true WTF?!?
Console.WriteLine(string.Empty.StartsWith(specialString));
Console.WriteLine(string.Empty.StartsWith(((char)10781).ToString()));

解决方法

您可以使用 ordinal StringComparison修复此错误:

来自MSDN文档:

When you specify either
StringComparison.Ordinal or
StringComparison.OrdinalIgnoreCase,
the string comparison will be
non-linguistic. That is,the features
that are specific to the natural
language are ignored when making
comparison decisions. This means the
decisions are based on simple byte
comparisons and ignore casing or
equivalence tables that are
parameterized by culture. As a result,
by explicitly setting the parameter to
either the StringComparison.Ordinal or
StringComparison.OrdinalIgnoreCase,
your code often gains speed,increases
correctness,and becomes more
reliable.

char specialChar = (char)10781;


    string specialString = Convert.ToString(specialChar);

    // prints 1
    Console.WriteLine(specialString.Length);

    // prints 10781
    Console.WriteLine((int)specialChar);

    // prints false
    Console.WriteLine(string.Empty.StartsWith("A"));

    // prints false
    Console.WriteLine(string.Empty.StartsWith(specialString,StringComparison.Ordinal));

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读