使用C#三元条件运算符进行必需的转换

前端之家收集整理的这篇文章主要介绍了使用C#三元条件运算符进行必需的转换前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我试图弄清楚为什么在以下示例中需要强制转换:
bool test = new Random().NextDouble() >= 0.5;
short val = 5;

// Ex 1 - must cast 0 to short
short res = test ? 5 : 0;  // fine
short res = test ? val : 0;  // error
short res = test ? val : (short)0;  // ugly

// Ex 2 - must cast either short or null to short?
short? nres = test ? val : null;  // error
short? nres = test ? (short?)val : null;  // ugly
short? nres = test ? val : (short?)null;  // ugly
short? nres = test ? val : default(short?);  // ugly

第一个例子对我来说似乎很疯狂.如果短i = 0;编译,为什么编译器不能在上面的代码中隐含地将0(或任何其他有效的短值)视为short?

第二个例子对我来说更有意义.我知道编译器无法确定=的右侧表达式的类型,但IMO在执行此操作时应考虑可空类型.

我想了解这些编译器错误背后是否存在实际推理.

解决方法

表达测试? val:0编译得很好.您在此行中收到错误,因为此表达式的类型为int,并且您尝试将其分配给short变量.这需要一个明确的演员.来自C#语言规范:

If an implicit conversion (§6.1) exists from X to Y,but not from Y to X,then Y is the type of the conditional expression.

另一个问题是,例如,为什么文字0可以在没有强制转换的情况下分配给一个短变量:

short i = 0;

必须使用三元运算符的结果:

bool test = new Random().NextDouble() >= 0.5;
short val = 5;
short i = (short)(test ? val : 0);

原因是第一次赋值是在编译时计算的,因为它只包含常量.在这种情况下,隐式常量表达式转换规则适用:

• A constant-expression (§7.19) of type int can be converted to type sbyte,byte,short,ushort,uint,or ulong,provided the value of the constant-expression is within the range of the destination type.

如果所有操作数都是常量,也可以在编译时评估三元运算符:

short i = true ? 0 : int.MaxValue;

在任何其他情况下,更严格的运行时转换规则适用.以下所有3个语句都会出现编译错误

int intVal = 0;
short shortVal = 0;
bool boolVal = true;

short i = true ? 0 : intVal;
short j = true ? shortVal : 0;
short k = boolVal ? 0 : 0;

作为参考,你可以看到Eric Lippert’s comments.

第二个例子需要处理Nullable<>作为一个特例,就像你已经注意到的那样.

原文链接:https://www.f2er.com/csharp/99168.html

猜你在找的C#相关文章