为什么每个Char静态"Is ..."都有一个字符串重载,例如IsWhiteSpace(string,Int32)?

wes*_*ton 15 c#

http://msdn.microsoft.com/en-us/library/1x308yk8.aspx

这允许我这样做:

var str = "string ";
Char.IsWhiteSpace(str, 6);
Run Code Online (Sandbox Code Playgroud)

而不是:

Char.IsWhiteSpace(str[6]);
Run Code Online (Sandbox Code Playgroud)

看起来很不寻常,所以我看了一下反思:

[TargetedPatchingOptOut("Performance critical to inline across NGen image boundaries")]
public static bool IsWhiteSpace(char c)
{
    if (char.IsLatin1(c))
    {
        return char.IsWhiteSpaceLatin1(c);
    }
    return CharUnicodeInfo.IsWhiteSpace(c);
}

[SecuritySafeCritical]
public static bool IsWhiteSpace(string s, int index)
{
    if (s == null)
    {
        throw new ArgumentNullException("s");
    }
    if (index >= s.Length)
    {
        throw new ArgumentOutOfRangeException("index");
    }
    if (char.IsLatin1(s[index]))
    {
        return char.IsWhiteSpaceLatin1(s[index]);
    }
    return CharUnicodeInfo.IsWhiteSpace(s, index);
}
Run Code Online (Sandbox Code Playgroud)

三件事让我印象深刻:

  1. 为什么只在上限进行限制检查呢?抛出一个ArgumentOutOfRangeException,而索引低于0将给出字符串的标准IndexOutOfRangeException
  2. 的precense SecuritySafeCriticalAttribute我读过关于一般blerb,但在这里做什么还不清楚,如果它链接到上限检查.
  3. TargetedPatchingOptOutAttribute其他Is...(char)方法不存在.例如IsLetter,IsNumber

Esa*_*ija 18

因为不是每个角色都适合C#焦炭.例如,""需要2 C#chars,并且您只能通过char重载获得有关该字符的任何信息.使用String和索引,方法可以查看索引i处的字符是否为高代理char,然后char在下一个索引处读取低代理,根据算法添加它们,并检索有关代码点的信息U+20000.

这就是UTF-16可以编码100万个不同代码点的方式,它是一种可变宽度编码.编码字符需要2-4个字节,或1-2 C#字符.