在C#中为什么不能有条件的经营者隐式转换为可空类型 [英] In C# why can't a conditional operator implicitly cast to a nullable type

查看:146
本文介绍了在C#中为什么不能有条件的经营者隐式转换为可空类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,为什么隐式转换的失败...

I am curious as to why an implicit cast fails in...

int? someValue = SomeCondition ? ResultOfSomeCalc() : null;

和为什么我要代替执行有明确的转换

and why I have to perform an explicit cast instead

int? someValue = SomeCondition ? ResultofSomeCalc() : (int?)null;

在我看来,编译器包含所有的信息就需要做一个隐式转换的决定,不是吗?

It seems to me that the compiler has all the information it need to make an implicit casting decision, no?

推荐答案

在C#3.0规范中的相关章节是7.13,条件运算符:

The relevant section of the C# 3.0 spec is 7.13, the conditional operator:

在第二和第三个操作数:操作员控制的条件前pression的类型。设X和Y是类型的第二和第三运算数的。然后,

The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,

如果X和Y是相同的类型,那么这是有条件的类型
否则,如果隐式转换(第6.1节)从X到Y的存在,但不能从Y到X,然后Y是有条件前pression的类型。
否则,如果(第6.1节)选自Y存在于X的隐式转换,但不能从X到Y,则X是有条件前pression的类型。
否则,没有前pression类型可确定,并发生编译时错误。

If X and Y are the same type, then this is the type of the conditional Otherwise, 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. Otherwise, if an implicit conversion (§6.1) exists from Y to X, but not from X to Y, then X is the type of the conditional expression. Otherwise, no expression type can be determined, and a compile-time error occurs.

这篇关于在C#中为什么不能有条件的经营者隐式转换为可空类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆