【问题标题】:Best C# method for checking for a null string value [duplicate]检查空字符串值的最佳 C# 方法
【发布时间】:2013-01-07 21:58:50
【问题描述】:

可能重复:
How to check if String is null

我只需要能够检查字符串内的null 值。我目前知道的最好的方法是String.IsNullOrEmpty(),它不适合我们正在尝试做的事情(string.empty 值是允许的,nulls 是不允许的)。有没有人有什么建议?

【问题讨论】:

标签: c# string null


【解决方案1】:

只需将您的字符串与null进行比较

bool stringIsNull = mystring == null;

这是一个适合你的扩展方法

public static class ExtensionMethods
{
    public static bool IsNull(this string str)
    {
        return str == null;
    }
}

【讨论】:

  • 如果 mystring 实际上为空,这不会抛出错误吗?
  • @NealR 不,它不会,它只会返回true
  • @NealR 不,它正在评估mystring == null,然后将stringIsNull 设置为该值。为了更明确:bool stringIsNull = (mystring == null)
  • @NealR 扩展方法实际上只是静态方法。所以在这种扩展方法的情况下:string a = null; a.IsNull() // true - no exception thrown 只是真的在做string a = null; ExtensionMethods.IsNull(a)
【解决方案2】:

您检查的方式与检查任何其他变量是否为空的方式相同:

if(variable == null)
{
  //do stuff
}

【讨论】:

    【解决方案3】:

    如果您想跳过null 值,只需使用!= null

    if(str != null)
    {
    
    }
    

    【讨论】:

      【解决方案4】:
      if (variable != null) 
       //do your action for not null
      else 
        //variable is null
      

      【讨论】:

        猜你喜欢
        • 2011-05-30
        • 1970-01-01
        • 2011-08-18
        • 1970-01-01
        • 1970-01-01
        • 2010-12-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多