[英]Converting if into ternary operator in C#
how can I convert this simple if statement into:?如何将这个简单的 if 语句转换为:? (ternary) operator in C#?
C# 中的(三元)运算符?
case "amount": { if(!Decimal.TryParse( fvm.Value,out a)) a=Decimal.MinValue; break; }
You can either assign the value of a
back to itself on success, or use a separate temporary variable (I'd prefer the latter):您可以在成功时将
a
的值分配给自身,也可以使用单独的临时变量(我更喜欢后者):
case: "amount":
a = decimal.TryParse(fvm.Value, out var tmp) ? tmp : decimal.MinValue;
break;
a = Decimal.TryParse( fvm.Value,out var tmp) ? tmp : Decimal.MinValue;
break;
I would personally prefer to create an helper method我个人更喜欢创建一个辅助方法
public static decimal? ParseDecimal(string str) => Decimal.TryParse(str, out var tmp) ? (decimal?)tmp : null;
since that would let you use the null-coalescing operator:因为这会让您使用空合并运算符:
a = ParceDecimal(fvm.Value) ?? decimal.MinValue
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.