如何检查C#变量是空字符串""还是null?

Sam*_*tar 94 c#

我正在寻找最简单的检查方法.我有一个可以等于""或null的变量.是否只有一个函数可以检查它是不是""还是空?

oop*_*ase 198

if (string.IsNullOrEmpty(myString)) {
   //
}
Run Code Online (Sandbox Code Playgroud)

  • @Lion Liu:实际上我认为PHP提供的功能完全一样.请参阅:http://php.net/manual/en/function.empty.php (5认同)
  • 我喜欢IsNullOrWhiteSpace(null,empty或whitespace ......) (4认同)
  • 非常简单实用.我希望PHP能有这样的东西 (3认同)
  • 非常清楚的是,您必须使用“string/String”的类函数,*不*尝试通过对象使用该函数!例如,“string foo;”将不允许您执行“foo.IsNullOrEmpty();”;你需要像 `string.IsNullOrEmpty(foo);` 这样使用它,当来自其他为其字符串对象内置了 null/0 长度检查的语言时,这有点烦人。 (3认同)
  • 当我使用 `IsEmpty` 时,它说:`'string' 不包含 IsEmpty` 的定义,我可以在 [msdn](https://msdn.microsoft.com/en-us/library/system) 中使用 `IsEmpty` .web.webpages.stringextensions.isempty%28v=vs.99%29.aspx) 还是我应该使用`IsNullOrEmpty`? (2认同)

mad*_*dd0 42

从.NET 2.0开始,您可以使用:

// Indicates whether the specified string is null or an Empty string.
string.IsNullOrEmpty(string value);
Run Code Online (Sandbox Code Playgroud)

此外,自.NET 4.0以来,有一种新方法更进一步:

// Indicates whether a specified string is null, empty, or consists only of white-space characters.
string.IsNullOrWhiteSpace(string value);
Run Code Online (Sandbox Code Playgroud)


jk.*_*jk. 9

如果变量是一个字符串

bool result = string.IsNullOrEmpty(variableToTest);
Run Code Online (Sandbox Code Playgroud)

如果你只有一个可能包含或不包含字符串的对象

bool result = string.IsNullOrEmpty(variableToTest as string);
Run Code Online (Sandbox Code Playgroud)