【问题标题】:How can I check whether a string variable is empty or null in C#? [duplicate]如何在 C# 中检查字符串变量是否为空或 null? [复制]
【发布时间】:2011-11-22 09:40:52
【问题描述】:

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

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

【问题讨论】:

  • 我特别认为你没有深入解释这一点。你说的是to "" or null,然后是not "" or null,这让我很反感。

标签: c# string isnullorempty


【解决方案1】:
if (string.IsNullOrEmpty(myString)) {
   //
}

【讨论】:

  • 当我使用IsEmpty 时,它说:'string' does not contain a definition for IsEmpty,我可以在msdn 中使用IsEmpty 还是应该使用IsNullOrEmpty
  • 非常简单实用。我希望 PHP 可以有这样的东西
  • @Lion Liu:实际上我认为 PHP 提供的功能也差不多。见:php.net/manual/en/function.empty.php
  • 我喜欢 IsNullOrWhiteSpace (null,empty, or whitespace...)
  • 为了超级清楚,你必须使用string/String的类函数,NOT试图通过对象使用函数!例如,string foo; 不允许你做foo.IsNullOrEmpty();;你需要像string.IsNullOrEmpty(foo); 一样使用它,当来自其他语言时,这有点烦人,这些语言已经为它们的字符串对象内置了 null/0-length-checks。
【解决方案2】:

从 .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);

【讨论】:

    【解决方案3】:

    如果变量是字符串

    bool result = string.IsNullOrEmpty(variableToTest);
    

    如果你只有一个可能包含也可能不包含字符串的对象,那么

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

    【讨论】:

    • 我遇到了同样的问题,第二个问题无法正常工作。试试这个:对象 x=3; bool result = string.IsNullOrEmpty(x as string); 'x as string' 将为 null,因此尽管 x 的值不是 null 或空字符串,但结果为真。我没有找到一个简短的解决方案,使用了双重检查。
    • @MártonMolnár 它必须包含一个字符串 3 不是一个字符串,所以这应该尝试使用“3”来代替
    【解决方案4】:

    string.IsNullOrEmpty 是你想要的。

    【讨论】:

      【解决方案5】:
      if (string.IsNullOrEmpty(myString)) 
      {
        . . .
        . . .
      }
      

      【讨论】:

        【解决方案6】:

        便宜的把戏:

        Convert.ToString((object)stringVar) == ""
        

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

        (或者,如果您使用的是 .NET 2.0,则可以始终使用 String.IsNullOrEmpty。)

        【讨论】:

        • 虽然技术上是正确的,但我可以断然地说我从未见过这种方法被使用过。
        • 我们是否假设将 stringVar 转换为强制转换对象会为分配给 stringVar 变量的 null 和空字符串返回空字符串,但是在没有强制转换的情况下转换相同的 stringVar 会返回 null 和空字符串?我只是想找出所有的变化.....
        猜你喜欢
        • 2019-01-25
        • 2016-09-13
        • 1970-01-01
        • 2013-01-21
        • 2012-04-13
        • 1970-01-01
        • 2020-10-17
        • 2011-01-23
        • 2010-09-27
        相关资源
        最近更新 更多