C# 中的三元运算符是否有 shorthand?
Is there a shorthand for the ternary operator in C#?
背景
在PHP中有一个shorthand用于三元运算符:
$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# 中,(据我所知)只有 "full" 版本有效:
string Value = "";
string Result = Value == string.Empty ? "value was empty" : Value;
所以我的问题是:C# 中是否有针对三元运算符的 shorthand,如果没有,是否有解决方法?
研究
我发现了以下问题,但它们指的是将三元运算符用作 shorthand 到 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的shorthand风格(语法错误失败)
string Value = "";
string Result = Value ?: "value was empty";
使用JS的shorthand风格(失败是因为“||
运算符不适用于string
和string
。")
string Value = "";
string Result = Value || "value was empty";
当字符串为空时没有shorthand。当字符串为 null
时有一个 shorthand :
string Value = null;
string Result = Value ?? "value was null";
合并 ??
运算符仅适用于 null
,但您可以 "customize" 使用扩展方法的行为:
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");
不过我觉得也没比三元好多少
注意:@
允许您使用保留字作为变量名。
背景
在PHP中有一个shorthand用于三元运算符:
$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# 中,(据我所知)只有 "full" 版本有效:
string Value = "";
string Result = Value == string.Empty ? "value was empty" : Value;
所以我的问题是:C# 中是否有针对三元运算符的 shorthand,如果没有,是否有解决方法?
研究
我发现了以下问题,但它们指的是将三元运算符用作 shorthand 到 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的shorthand风格(语法错误失败)
string Value = "";
string Result = Value ?: "value was empty";
使用JS的shorthand风格(失败是因为“||
运算符不适用于string
和string
。")
string Value = "";
string Result = Value || "value was empty";
当字符串为空时没有shorthand。当字符串为 null
时有一个 shorthand :
string Value = null;
string Result = Value ?? "value was null";
合并 ??
运算符仅适用于 null
,但您可以 "customize" 使用扩展方法的行为:
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");
不过我觉得也没比三元好多少
注意:@
允许您使用保留字作为变量名。