2012-04-20 99 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()); 
     } 
    }