If string is not null or empty else 一个衬里 [英] One liner for If string is not null or empty else

查看:24
本文介绍了If string is not null or empty else 一个衬里的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;
}

并像这样使用它:

FooTextBox.Text = NonBlankValueOf(strFoo);

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

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

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

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

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

For your need specifically, there is the conditional operator bool expr ? true_value : false_value that you can use to simplify if/else statement blocks that set or return a value.

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

这篇关于If string is not null or empty else 一个衬里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆