C#为什么不能将可为null的int赋值为null [英] c# why can't a nullable int be assigned null as a value

查看:496
本文介绍了C#为什么不能将可为null的int赋值为null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

解释为什么不能为可为null的int分配空值,例如

Explain why a nullable int can't be assigned the value of null e.g

int? accom = (accomStr == "noval" ? null  : Convert.ToInt32(accomStr));

该代码出了什么问题?

推荐答案

问题不是不能将null分配给int吗?问题在于三元运算符返回的两个值必须为同一类型,或者一个必须隐式转换为另一个。在这种情况下,不能将null隐式转换为int,反之亦然,因此必须进行显式强制转换。尝试以下操作:

The problem isn't that null cannot be assigned to an int?. The problem is that both values returned by the ternary operator must be the same type, or one must be implicitly convertible to the other. In this case, null cannot be implicitly converted to int nor vice-versus, so an explict cast is necessary. Try this instead:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));

这篇关于C#为什么不能将可为null的int赋值为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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