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

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

概述我试图弄清楚为什么在以下示例中需要强制转换: bool test = new Random().NextDouble() >= 0.5;short val = 5;// Ex 1 - must cast 0 to shortshort res = test ? 5 : 0; // fineshort res = test ? val : 0; // errorshort res = 我试图弄清楚为什么在以下示例中需要强制转换:
bool test = new Random().NextDouble() >= 0.5;short val = 5;// Ex 1 - must cast 0 to shortshort res = test ? 5 : 0;  // fineshort res = test ? val : 0;  // errorshort res = test ? val : (short)0;  // ugly// Ex 2 - must cast either short or null to short?short? nres = test ? val : null;  // errorshort? nres = test ? (short?)val : null;  // uglyshort? nres = test ? val : (short?)null;  // uglyshort? 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<>作为一个特例,就像你已经注意到的那样.

总结

以上是内存溢出为你收集整理的使用C#三元条件运算符进行必需的转换全部内容,希望文章能够帮你解决使用C#三元条件运算符进行必需的转换所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1243030.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-06
下一篇2022-06-06

发表评论

登录后才能评论

评论列表(0条)

    保存