有没有理由在String.IsNullOrEmpty()上使用这个Regex方法?

Mat*_*nes 1 c# string asp.net-3.5

我有一个名为isStringOnlyWhitespace()的方法:

public static bool isStringOnlyWhitespace(string toEval)
{
    string stringNoWhitespace = Regex.Replace(toEval, @"\s", "");
    if (stringNoWhitespace.Length > 0) return false;
    else return true;
}
Run Code Online (Sandbox Code Playgroud)

是否有任何理由使用此方法检查String.IsNullOrEmpty()上的空/空字符串?

Mat*_*eer 10

当然,如果您正在拍摄更难以阅读的较慢代码:)

你真的想用string.IsNullOrWhitespace.编写该代码的人可能在此方法存在之前就已经这样做了.但即便如此,myString.Trim().Length == 0在这种情况下我更愿意.

  • `string.IsNullOrWhitespace`是在.NET 4.0中引入的,所以旧版本只能使用`string.IsNullOrEmpty`. (5认同)