2010-05-25 49 views
4

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

例如

string a; 

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

你从哪里听说过C#.Net?哪有这回事。 – 2010-05-25 09:01:52

回答

7

对于字符串,有

if (String.IsNullOrEmpty(a)) 
+2

更好的使用String.IsNullOrEmpty() – 2010-05-25 09:30:36

+0

'string'击败'String',因为你不必按shift键,让你的键盘保持更长的时间,并且让你不那么累,再加上你不需要'使用System;为小写版本。 (开玩笑,申请和+1正确的大写当清楚地访问一个静态类方法) – 2011-12-06 09:19:28

1

从2.0版本,你可以使用IsNullOrEmpty

string a; 
... 
if (string.IsNullOrEmpty(a)) ... 
0

字符串:

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

特定类型,你可以创建一种推广方法 请注意,我用的HasValue代替IsNullorEmpty因为时间的99%,你将不得不使用! - 运算符如果使用IsNullOrEmpty我觉得这很不可读

public static bool HasValue(this MyType value) 
{ 
//do some testing to see if your specific type is considered filled 
} 
3

您可以定义一个扩展方法,让你做这个事情太多了:

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

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

+2

引用约翰Skeet: 但是,你一定要使用Any()。这样它只需要测试第一个元素的存在。对于正常实现ICollection ,这将非常便宜,但对于涉及复杂查询的情况,可能会比Count()快得多*。 http://danielvaughan.orpius.com/post/IEnumerable-IsNullOrEmpty.aspx – 2010-05-25 10:01:17

0
if(string.IsNullOrEmpty(string name)) 
{ 
    /// write ur code 
} 
0

我发现Apache的Commons.Lang StringUtils的(JAVA)的命名轻松了不少:isEmpty()检测为null或空字符串,的isBlank()检查空,空字符串或空格只。 isNullOrEmpty可能更具描述性,但空和空,在大多数情况下,您使用它,同样的事情。