【问题标题】:One liner for If string is not null or empty elseIf string is not null or empty else
【发布时间】:2013-03-27 13:47:38
【问题描述】:

出于各种原因,我通常在整个应用程序中使用这样的东西:

if (String.IsNullOrEmpty(strFoo))
{
     FooTextBox.Text = "0";
}
else
{
     FooTextBox.Text = strFoo;
}

如果我要经常使用它,我将创建一个返回所需字符串的方法。例如:

public string NonBlankValueOf(string strTestString)
{
    if (String.IsNullOrEmpty(strTestString))
        return "0";
    else
        return strTestString;
}

并像这样使用它:

FooTextBox.Text = NonBlankValueOf(strFoo);

我一直想知道是否有 C# 的一部分可以为我做这件事。可以这样称呼的东西:

FooTextBox.Text = String.IsNullOrEmpty(strFoo,"0")

第二个参数是String.IsNullOrEmpty(strFoo) == true的返回值

如果没有,有人有更好的方法吗?

【问题讨论】:

  • FooTextBox.Text = foo.IsNullOrEmpty ? "0" : foo;
  • 使用 IsNullOrWhiteSpace 修剪字符串。
  • 我不会更改您的代码,除非将 NonBlankValueOf 设为静态。不要依赖 C# 可能提供的东西 - 方法 NonBlankValueOf 对您的应用程序具有特定含义,并且您可以控制该含义。例如,如果有一天您需要将“0”更改为“1”怎么办?

标签: c# if-statement isnullorempty


【解决方案1】:

有一个空合并运算符 (??),但它不能处理空字符串。

如果你只对处理空字符串感兴趣,你会像这样使用它

string output = somePossiblyNullString ?? "0";

根据您的具体需要,您可以使用条件运算符 bool expr ? true_value : false_value 来简化设置或返回值的 if/else 语句块。

string output = string.IsNullOrEmpty(someString) ? "0" : someString;

【讨论】:

  • +1 是何时使用空合并的一个很好的例子,尽管 OP 可能需要它来捕获他/她的情况下的空字符串。
  • 有没有办法做这第二件事(字符串输出 = string.IsNullOrEmpty(someString) ? "0" : someString;),但如果 'someString' 是一个表达式,那么捕获的结果那个表达式并最终返回它?我还没有在这方面找到任何东西,但发现它会非常有用。
【解决方案2】:

你可以使用ternary operator:

return string.IsNullOrEmpty(strTestString) ? "0" : strTestString

FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;

【讨论】:

    【解决方案3】:

    您可以为 String 类型编写自己的 Extension 方法:-

     public static string NonBlankValueOf(this string source)
     {
        return (string.IsNullOrEmpty(source)) ? "0" : source;
     }
    

    现在你可以像使用任何字符串类型一样使用它了

    FooTextBox.Text = strFoo.NonBlankValueOf();
    

    【讨论】:

    • 感谢您的功能:)
    【解决方案4】:

    这可能会有所帮助:

    public string NonBlankValueOf(string strTestString)
    {
        return String.IsNullOrEmpty(strTestString)? "0": strTestString;
    }
    

    【讨论】:

      【解决方案5】:

      老问题,但我想我会添加这个来帮忙,

      #if DOTNET35
      bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
      #else
      bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
      #endif
      

      【讨论】:

        【解决方案6】:

        您可以通过 C#8/9 中的 switch 表达式进行模式匹配来实现此目的

        FooTextBox.Text = strFoo switch
        {
            { Length: >0 } s => s, // If the length of the string is greater than 0 
            _ => "0" // Anything else
        };
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-09-24
          • 1970-01-01
          • 2022-12-26
          • 2014-12-08
          • 2022-12-15
          • 2016-05-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多