2012-04-20 24 views
3

伙计们, 我string.IsNullOrWhiteSpace望着的实施:.NET 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; 
} 

此实现是否不正确?它是否有性能损失?

+2

这是本质它在做什么 - 你是** **不看真正的源代码,正是从反射 – BrokenGlass 2012-04-20 17:57:39

+0

收集你的意思是字符串或炭? – 2012-04-20 17:57:40

回答

15

原代码(从参考源)是

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

你看到一个贫穷的反编译器的输出。

+6

请注意,这可以用下面的代码大大缩短:'返回值== null || value.All(Char.IsWhiteSpace);' – 2013-03-22 21:41:41

+0

@SLaks - 您可以添加一个链接或“参考源”的文档? – 2014-03-07 17:37:14

+1

@CalebBell:http://referencesource.microsoft.com/#mscorlib/system/string.cs#55e241b6143365ef – SLaks 2014-03-07 17:38:22

8

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

2

它必须是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; 
    } 
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()); 
     } 
    }