编写健壮代码以便检查变量是否为空和空白的最佳方法是什么。
例如
string a;
if((a != null) && (a.Length() > 0))
{
//do some thing with a
}
编写健壮代码以便检查变量是否为空和空白的最佳方法是什么。
例如
string a;
if((a != null) && (a.Length() > 0))
{
//do some thing with a
}
对于字符串,有
if (String.IsNullOrEmpty(a))
您可以定义一个扩展方法来允许您在许多事情上执行此操作:
static public bool IsNullOrEmpty<T>(this IEnumerable <T>input)
{
return input == null || input.Count() == 0;
}
System.String
正如已经指出的那样,它已经作为字符串类的静态方法存在。
如果您使用的是 .NET 4.0,您可能想看看String.IsNullOrWhiteSpace。
从 2.0 版开始,您可以使用IsNullOrEmpty。
string a;
...
if (string.IsNullOrEmpty(a)) ...
对于字符串:
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
}
if(string.IsNullOrEmpty(string name))
{
/// write ur code
}
我发现 Apache Commons.Lang StringUtils (Java) 的命名要容易得多:isEmpty() 检查 null 或空字符串,isBlank() 检查 null、空字符串或仅空格。isNullOrEmpty 可能更具描述性,但在大多数情况下,空和 null 是相同的东西。