简体   繁体   English

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

[英]Is there a shorthand for the ternary operator in C#?

Background 背景

In PHP there is a shorthand for the ternary operator: 在PHP中,三元运算符有一个简写形式:

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

In JS there's also an equivalent: 在JS中也有一个等效项:

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

But in C#, there's (as far as i know) only the "full" version works: 但是在C#中,(据我所知)只有“完整”版本有效:

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

So my question is: Is there a shorthand for the ternary operator in C#, and if not, is there a workaround? 所以我的问题是:C#中是否存在三元运算符的简写,如果没有,是否有解决方法?

Research 研究

I found the following questions, but they're referring to use the ternary operator as shorthand to if-else: 我发现了以下问题,但它们是指将三元运算符用作if-else的简写:

shorthand If Statements: C# 简写If语句:C#

Benefits of using the conditional ?: (ternary) operator 使用条件?:(三元)运算符的好处

And this one, but it's concerning Java: 这是关于Java的:

Is there a PHP like short version of the ternary operator in Java? 在Java中是否有类似PHP的三元运算符的简短版本?

What I have tried 我尝试过的

Use the shorthand style of PHP (Failed due to syntax error) 使用PHP的简写样式(由于语法错误而失败)

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

Use the shorthand style of JS (Failed because " The || operator is not applicable to string and string . ") 使用JS的简写样式(失败,因为“ ||运算符不适用于stringstring ”)

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

There is no shorthand for when the string is empty. 字符串为空时没有简写形式。 There is a shorthand for when the string is null : 字符串为null时有一个简写形式:

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

The coalesce ?? 合并?? operator works only on null , but you could "customize" the behavior with an extension method: 运算符仅对null起作用,但是您可以使用扩展方法“自定义”行为:

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

and you use it like this: 您可以像这样使用它:

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

But I don't think it is much better than the ternary. 但是我认为这并不比三元更好。

Note: the @ allows you to use reserved words as variable names. 注意: @允许您将保留字用作变量名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM