2011-11-22 271 views

回答

110
if (string.IsNullOrEmpty(myString)) { 
    // 
} 
+1

当我使用'IsEmpty'它说:''字符串'不包含IsEmpty'的定义,我可以在[msdn]中使用'IsEmpty'(https://msdn.microsoft.com/zh-cn/library/system.web.webpages.stringextensions .isempty%28v = vs.99%29.aspx)还是应该使用'IsNullOrEmpty'? – stom

+2

非常简单而实用。我希望PHP可以有这样的东西 –

+3

@Lion Liu:其实我认为PHP提供的东西完全一样。请参阅:http://php.net/manual/en/function.empty.php – Milan

6

如果变量是一个字符串

bool result = string.IsNullOrEmpty(variableToTest); 

,如果你只有一个对象可能会或可能不会包含一个字符串,然后

bool result = string.IsNullOrEmpty(variableToTest as string); 
+1

我有同样的问题,第二个不能正常工作。试试这个: object x = 3; bool result = string.IsNullOrEmpty(x as string); 'x as string'将为空,因此尽管x的值不是null或空字符串,但结果仍然为真。我没有找到一个简短的解决方案,使用双重检查。 –

+0

@MártonMolnár它将不得不包含一个字符串3不是一个字符串,所以这是预计尝试使用“3”而不是 –

1

把戏:

Convert.ToString((object)stringVar) == “” 

这是可行的,因为Convert.ToString(object )如果object为null,则返回一个空字符串。 Convert.ToString(string)如果string为null,则返回null。

(或者,如果你使用.NET 2.0,你可以使用总是String.IsNullOrEmpty。)

+4

尽管技术上正确,但我可以断然说我从来没有见过这种方法使用。 –

+0

为什么?........... – Liam

+0

我们是否认为将stringVar转换为一个强制转换对象会返回空字符串,分配给stringVar变量的空字符串和空字符串,强制转换返回null和空字符串?我只是想找出所有的变化..... – Stokely

28

由于.NET 2.0,你可以使用:

// Indicates whether the specified string is null or an Empty string. 
string.IsNullOrEmpty(string value); 

此外,由于.NET 4.0有这么去更远一些的新方法:

// Indicates whether a specified string is null, empty, or consists only of white-space characters. 
string.IsNullOrWhiteSpace(string value); 
1
if (string.IsNullOrEmpty(myString)) 
{ 
    . . . 
    . . . 
} 
相关问题