If string的一个衬里不为null或为空 [英] One liner for If string is not null or empty else
问题描述
我通常在整个应用程序中出于各种原因使用类似的东西:
if(String.IsNullOrEmpty(strFoo))
{
FooTextBox.Text =0;
}
其他
{
FooTextBox.Text = strFoo;
}
如果我要经常使用它,我会创建一个方法返回所需的字符串。例如:
public string NonBlankValueOf(string strTestString)
{
if(String.IsNullOrEmpty(strTestString) ))
返回0;
else
返回strTestString;
}
并使用它:
FooTextBox.Text = NonBlankValueOf(strFoo);
我总是想知道是否有某些东西属于C#的一部分会为我做这件事。可以调用的东西如下:
FooTextBox.Text = String.IsNullOrEmpty(strFoo,0)
<如果 String.IsNullOrEmpty(strFoo)== true
如果没有人有更好的方法吗?
解决方案有一个空的合并运算符( ??
),但它不会处理空字符串。
<如果你只对处理空字符串感兴趣,你可以使用它像 string output = somePossiblyNullString ?? 0;
根据具体需要,只需条件运算符 bool expr? true_value:false_value
您可以使用简单的if / else语句块来设置或返回值。
string output = string.IsNullOrEmpty(someString)? 0:someString;
I usually use something like this for various reasons throughout an application:
if (String.IsNullOrEmpty(strFoo))
{
FooTextBox.Text = "0";
}
else
{
FooTextBox.Text = strFoo;
}
If I'm going to be using it a lot I will create a method that returns the desired string. For example:
public string NonBlankValueOf(string strTestString)
{
if (String.IsNullOrEmpty(strTestString))
return "0";
else
return strTestString;
}
and use it like:
FooTextBox.Text = NonBlankValueOf(strFoo);
I always wondered if there was something that was part of C# that would do this for me. Something that could be called like:
FooTextBox.Text = String.IsNullOrEmpty(strFoo,"0")
the second parameter being the returned value if String.IsNullOrEmpty(strFoo) == true
If not does anyone have any better approaches they use?
解决方案 There is a null coalescing operator (??
), but it would not handle empty strings.
If you were only interested in dealing with null strings, you would use it like
string output = somePossiblyNullString ?? "0";
For your need specifically, there is simply the conditional operator bool expr ? true_value : false_value
that you can use to simply if/else statement blocks that set or return a value.
string output = string.IsNullOrEmpty(someString) ? "0" : someString;
这篇关于If string的一个衬里不为null或为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!