本文介绍了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作为值
发布评论