加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

当变量类型为[int?]时,为什么必须在C#中转换为(int?)

发布时间:2020-12-16 00:06:53 所属栏目:百科 来源:网络整理
导读:有人可以解释一下为什么我必须将null转换为int的逻辑原因? 当左参数类型可以有它们的两种类型? 做了两件事 int? k = (DateTime.Now.Ticks%5 3 ? 1 : null); 我必须这样做 int? k = (DateTime.Now.Ticks%5 3 ? 1 : (int?) null); 虽然int? k = null完全有
有人可以解释一下为什么我必须将null转换为int的逻辑原因?

当左参数类型可以有它们的两种类型?

做了两件事

int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : null);

我必须这样做

int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : (int?) null);

虽然int? k = null完全有效.

一个相反的例子:

我没有必要这样做:

string k =(DateTime.Now.Ticks%5> 3?“lala”:null);

解决方法

int? k = (DateTime.Now.Ticks%5 > 3 ? 1 : (int?) null);

在这种情况下,我们有1是int,null实际上是null
现在混淆是三元运算符被混淆为返回类型int或者是null,因为它的int它不会接受null

所以你需要将它转换为可以为空的int

现在在另一种情况下,你有一个字符串,null对于一个字符串是完全可以接受的

进一步的解释可以在Type inference – Eric找到

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,

  • If X and Y are the same type,then this is the type of the conditional expression.

  • Otherwise,if an implicit conversion 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 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读