可能重复:
Easier way of writing null or empty?如何检查C#变量是否为空字符串“”或null?
我找做检查的最简单方式。我有一个可以等于“”或null的变量。是否只有一个函数可以检查它是不是“”或null?
可能重复:
Easier way of writing null or empty?如何检查C#变量是否为空字符串“”或null?
我找做检查的最简单方式。我有一个可以等于“”或null的变量。是否只有一个函数可以检查它是不是“”或null?
if (string.IsNullOrEmpty(myString)) {
//
}
如果变量是一个字符串
bool result = string.IsNullOrEmpty(variableToTest);
,如果你只有一个对象可能会或可能不会包含一个字符串,然后
bool result = string.IsNullOrEmpty(variableToTest as string);
我有同样的问题,第二个不能正常工作。试试这个: object x = 3; bool result = string.IsNullOrEmpty(x as string); 'x as string'将为空,因此尽管x的值不是null或空字符串,但结果仍然为真。我没有找到一个简短的解决方案,使用双重检查。 –
@MártonMolnár它将不得不包含一个字符串3不是一个字符串,所以这是预计尝试使用“3”而不是 –
把戏:
Convert.ToString((object)stringVar) == “”
这是可行的,因为Convert.ToString(object )如果object为null,则返回一个空字符串。 Convert.ToString(string)如果string为null,则返回null。
(或者,如果你使用.NET 2.0,你可以使用总是String.IsNullOrEmpty。)
string.IsNullOrEmpty
是你想要的。
由于.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);
if (string.IsNullOrEmpty(myString))
{
. . .
. . .
}
当我使用'IsEmpty'它说:''字符串'不包含IsEmpty'的定义,我可以在[msdn]中使用'IsEmpty'(https://msdn.microsoft.com/zh-cn/library/system.web.webpages.stringextensions .isempty%28v = vs.99%29.aspx)还是应该使用'IsNullOrEmpty'? – stom
非常简单而实用。我希望PHP可以有这样的东西 –
@Lion Liu:其实我认为PHP提供的东西完全一样。请参阅:http://php.net/manual/en/function.empty.php – Milan