73

私は通常、アプリケーション全体でさまざまな理由でこのようなものを使用します。

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")

2番目のパラメーターは、次の場合の戻り値です。String.IsNullOrEmpty(strFoo) == true

そうでない場合、誰かが彼らが使用するより良いアプローチを持っていますか?

4

6 に答える 6

155

null合体演算子(??)がありますが、空の文字列は処理されません。

null文字列の処理のみに関心がある場合は、次のように使用します。

string output = somePossiblyNullString ?? "0";

特に必要に応じてbool expr ? true_value : false_value、値を設定または返すif/elseステートメントブロックを簡略化するために使用できる条件演算子があります。

string output = string.IsNullOrEmpty(someString) ? "0" : someString;
于 2013-03-27T13:49:22.033 に答える
16

三項演算子を使用できます:

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

FooTextBox.Text = string.IsNullOrEmpty(strFoo) ? "0" : strFoo;
于 2013-03-27T13:49:44.933 に答える
10

String型の独自のExtensionメソッドを作成できます:-

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

これで、他の文字列タイプと同じように使用できます

FooTextBox.Text = strFoo.NonBlankValueOf();
于 2013-03-27T13:52:34.437 に答える
8

これは役立つかもしれません:

public string NonBlankValueOf(string strTestString)
{
    return String.IsNullOrEmpty(strTestString)? "0": strTestString;
}
于 2013-03-27T13:49:33.620 に答える
0

古い質問ですが、これを追加して支援すると思いましたが、

#if DOTNET35
bool isTrulyEmpty = String.IsNullOrEmpty(s) || s.Trim().Length == 0;
#else
bool isTrulyEmpty = String.IsNullOrWhiteSpace(s) ;
#endif
于 2014-09-12T21:19:38.657 に答える
0

これは、C#8/9のスイッチ式とのパターンマッチングで実現できます。

FooTextBox.Text = strFoo switch
{
    { Length: >0 } s => s, // If the length of the string is greater than 0 
    _ => "0" // Anything else
};
于 2020-11-12T16:59:52.267 に答える