6

伙计们,我正在查看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;
}

问:是不是太复杂了?下面的实现不能做同样的工作并且更容易看:

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;
}

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

4

4 回答 4

19

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

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;
}

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

于 2012-04-20T17:58:09.507 回答
8

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

于 2012-04-20T17:57:10.413 回答
3

它必须是 typedescriptor 的反汇编程序。

当我使用 JetBrain 的 dotPeek 查看相同的功能时,它看起来像这样:

 public static bool IsNullOrWhiteSpace(string value)
    {
      if (value == null)
        return true;
      for (int index = 0; index < value.Length; ++index)
      {
        if (!char.IsWhiteSpace(value[index]))
          return false;
      }
      return true;
    }
于 2012-04-20T18:02:37.817 回答
2

下面显示的是旧版本所需的扩展方法。我不确定我从哪里获得代码:

public static class StringExtensions
    {
        // This is only need for versions before 4.0
        public static bool IsNullOrWhiteSpace(this string value)
        {
            if (value == null) return true;
            return string.IsNullOrEmpty(value.Trim());
        }
    }
于 2012-04-20T18:11:00.373 回答