.NET string.IsNullOrWhiteSpace实现

epi*_*isx 6 .net c# string c#-4.0

伙计们,我正在查看string.IsNullOrWhiteSpace的实现:

http://typedescriptor.net/browse/types/9331-System.String

这是实施:

public static bool IsNullOrWhiteSpace(string value)
{
    if (value == null)
    {
        return true;
    }
    for (int i = 0; i < value.Length; i++)
    {
        if (char.IsWhiteSpace(value[i]))
        {
        }
        else
        {
            goto Block_2;
        }
    }
    goto Block_3;
    Block_2:
    return false;
    Block_3:
    return true;
}
Run Code Online (Sandbox Code Playgroud)

问题:这不是很复杂吗?以下实现无法完成相同的工作并且更容易实现:

bool IsNullOrWhiteSpace(string value)
{
    if(value == null)
    {
        return true;
    }   
    for(int i = 0; i < value.Length;i++)
    {
        if(!char.IsWhiteSpace(value[i]))
        {
            return false;
        }
    }
    return true;
}
Run Code Online (Sandbox Code Playgroud)

这个实现不正确吗?它是否有性能损失?

SLa*_*aks 17

原始代码(来自参考源)是

public static bool IsNullOrWhiteSpace(String value) {
    if (value == null) return true; 

    for(int i = 0; i < value.Length; i++) { 
        if(!Char.IsWhiteSpace(value[i])) return false; 
    }

    return true;
}
Run Code Online (Sandbox Code Playgroud)

你看到一个糟糕的反编译器的输出.

  • 请注意,使用以下代码可以大大缩短这一点:`return value == null || value.All(Char.IsWhiteSpace);` (6认同)

Chr*_*ain 8

您正在查看从反汇编的IL重新创建的C#.我确信实际的实现更接近您的示例,并且不使用标签.