【问题标题】:Is there a shorthand for the ternary operator in C#?C# 中的三元运算符有简写吗?
【发布时间】:2017-09-12 10:40:55
【问题描述】:

背景

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

【问题讨论】:

  • 但是三元运算符是简写的。敲一行代码真的有那么难吗?
  • 您的示例利用了真假值的原则,这个概念(默认情况下)不存在于强类型 C# 中。
  • value || "value was empty" 不是三元运算符的简写。这是一个逻辑陈述。这不是一回事。 Javascript 只是倾向于强制值,因为它不是强类型的,不像 c#

标签: c# ternary-operator


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    coalesce ?? 运算符仅适用于 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");
    

    但我认为它并不比三进制好多少。

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

    【讨论】:

      猜你喜欢
      • 2012-08-02
      • 2013-04-13
      • 2023-03-11
      • 2020-09-12
      • 2011-02-15
      • 2021-10-25
      • 2011-03-16
      相关资源
      最近更新 更多