C#为什么不能一个可空INT被分配null作为值 [英] c# why cant a nullable int be assigned null as a value

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

问题描述

有人能向我解释为什么一个可空INT不能被赋值为null值例如

Can someone explain to me why a nullable int cant be assigned the value of null e.g

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

什么是错的code?

What's wrong with that code?

推荐答案

问题是不是空不能被分配​​到一个int?问题是,由三元运算符返回这两个值必须是同一类型,或者必须是隐式转换为其他的。在这种情况下,空不能隐式转换成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#为什么不能一个可空INT被分配null作为值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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