4

编写健壮代码以便检查变量是否为空和空白的最佳方法是什么。

例如

string a;

if((a != null) && (a.Length() > 0))
{
    //do some thing with a
}
4

7 回答 7

7

对于字符串,有

if (String.IsNullOrEmpty(a))
于 2010-05-25T08:59:22.403 回答
3

您可以定义一个扩展方法来允许您在许多事情上执行此操作:

static public bool IsNullOrEmpty<T>(this IEnumerable <T>input)
{
    return input == null || input.Count() == 0;
}

System.String正如已经指出的那样,它已经作为字符串类的静态方法存在。

于 2010-05-25T09:03:26.140 回答
3

如果您使用的是 .NET 4.0,您可能想看看String.IsNullOrWhiteSpace

于 2010-05-25T09:04:59.160 回答
1

从 2.0 版开始,您可以使用IsNullOrEmpty

string a;
...
if (string.IsNullOrEmpty(a)) ...
于 2010-05-25T09:00:21.667 回答
0

对于字符串:

string a;
if(!String.IsNullOrEmpty(a))
{
//do something with a
}

对于特定类型,您可以创建一个扩展方法请注意,我使用 HasValue 而不是 IsNullorEmpty,因为如果您使用 IsNullOrEmpty,99% 的时间您将不得不使用 !-operator,我觉得这很不可读

public static bool HasValue(this MyType value)
{
//do some testing to see if your specific type is considered filled
}
于 2010-05-25T09:03:22.033 回答
0
if(string.IsNullOrEmpty(string name))
{
   ///  write ur code
}
于 2010-05-25T09:08:22.227 回答
0

我发现 Apache Commons.Lang StringUtils (Java) 的命名要容易得多:isEmpty() 检查 null 或空字符串,isBlank() 检查 null、空字符串或仅空格。isNullOrEmpty 可能更具描述性,但在大多数情况下,空和 null 是相同的东西。

于 2010-05-25T09:53:05.557 回答