C#中的三元运算符是否有简写?

时间:2017-09-12 10:40:55

标签: c# ternary-operator

背景

在PHP中,有一个三元运算符的简写:

$value = "";
echo $value ?: "value was empty"; // same as $value == "" ? "value was empty" : $value;

在JS中,还有一个等价物:

var value = "";
var ret = value || "value was empty"; // same as var ret = value == "" ? "value was empty" : value;

但是在C#中,(据我所知)只有"完全"版本有效:

string Value = "";
string Result = Value == string.Empty ? "value was empty" : Value;

所以我的问题是:C#中是否有三元运算符的简写,如果没有,是否有解决方法?

研究

我发现了以下问题,但他们指的是使用三元运算符作为if-else的简写:

shorthand If Statements: C#

Benefits of using the conditional ?: (ternary) operator

这个,但是关于Java:

Is there a PHP like short version of the ternary operator in Java?

我尝试了什么

使用PHP的速记样式(由于语法错误而失败)

string Value = "";
string Result = Value ?: "value was empty";

使用JS的速记样式(失败,因为" ||运算符不适用于stringstring" )

string Value = "";
string Result = Value || "value was empty";

2 个答案:

答案 0 :(得分:12)

字符串为空时没有简写。字符串为null时有简写:

string Value = null;
string Result = Value ?? "value was null";

答案 1 :(得分:4)

合并??运算符仅适用于null,但您可以使用扩展方法“自定义”该行为:

public static class StringExtensions
{
    public static string Coalesce(this string value, string @default)
    {
        return string.IsNullOrEmpty(value)
            ? value
            : @default;
    }
}

你可以这样使用它:

var s = stringValue.Coalesce("value was empty or null");

但我认为它不比三元组好得多。

注意:@允许您将保留字用作变量名。

相关问题