2011-10-02 175 views
8

我确定我在这里错过了一些东西。对于某个项目,我需要检查一个字符串是空还是空。更简单的方式写空或空?

有没有更简单的方法来写这个?

if(myString == "" || myString == null) 
{ 
    ... 
+0

我确实搜索过。有时候非常明显的东西会在雷达之下滑落。 – Phil

+1

问题done't应该-ve标记,添加一个链接[String.IsNullOrEmpty](http://msdn.microsoft.com/en-us/library/system.string.isnullorempty%28v=vs.110%29.aspx ) –

回答

26

是的,有整整这已经是String.IsNullOrEmpty helper方法:

if (String.IsNullOrEmpty(myString)) { 
    ... 
} 
+1

并在相关说明:http://stackoverflow.com/questions/2552350/string-isnullorempty-check-for-space/2552381#2552381 – xanatos

0

如果你是在.NET 4中,你可以使用

if(string.IsNullOrWhiteSpace(myString)){ 

} 

其他:

if(string.IsNullOrEmpty(myString)){ 

} 
+5

'IsNullOrWhiteSpace'检查别的东西,而不是等于'“”'所以它会有不同于问题中代码片段的语义。 – Joey

5
if (string.IsNullOrEmpty(myString)) { 
    ... 
} 

或者你也可以采取在扩展方法一个怪癖的优势,它们允许为空:

static class Extensions { 
    public static bool IsEmpty(this string s) { 
     return string.IsNullOrEmpty(s); 
    } 
} 

,然后让你写:

if (myString.IsEmpty()) { 
    ... 
} 

虽然你可能应该选择另一名称比'空'。

+0

扩展方法的好例子!谢谢! – Phil

+0

为什么不'string.IsNullOrEmpty(s)'而不是's == null || s == string.Empty'? – Nawaz

+0

你当然是对的:) –

-1

//如果字符串没有被定义为空,然后IsNullOrEmpty它的伟大工程,但如果字符串被定义为null,则修剪会抛出异常。

if(string.IsNullOrEmpty(myString.Trim()){ 
... 
} 

//你可以使用IsNullOrWhiteSpace这对于字符串多个空格做工精良.i.e其多个空格也

if(string.IsNullOrWhiteSpace (myString.Trim()){ 
    ... 
    } 
+1

“Trim”不是一个独立的函数,它是String的一个实例方法。正确的用法:'myString.Trim()',但是当mystring为空时会爆炸。使用'String.IsNullOrWhiteSpace()' –

+0

我同意你,所以我已经纠正了上面的代码。谢谢@HansKesting – Dipitak

0

返回true,为了避免null检查,你可以使用?运营商。

var result = value ?? ""; 

我经常用它作为警卫避免,我不希望在方法的数据发送。

JoinStrings(value1 ?? "", value2 ?? "") 

它也可以用来避免不必要的格式。

string ToString() 
{ 
    return "[" + (value1 ?? 0.0) + ", " + (value2 ?? 0.0) + "]"; 
} 

这也可以在if语句中使用,它不是很好,但有时可以得心应手。

if (value ?? "" != "") // Not the best example. 
{ 
}