C#为什么不能一个可空INT被分配null作为值

编程入门 行业动态 更新时间:2024-10-26 22:22:41
本文介绍了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作为值

本文发布于:2023-11-06 04:12:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562684.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:分配   INT   null

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!