c# 为什么不能将可为空的 int 分配为 null 作为值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/330471/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
c# why can't a nullable int be assigned null as a value
提问by mancmanomyst
Explain why a nullable int can't be assigned the value of null e.g
解释为什么不能为 nullable int 分配 null 的值,例如
int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr));
What's wrong with that code?
那个代码有什么问题?
采纳答案by Harry Steinhilber
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:
问题不在于 null 不能分配给 int?。问题是三元运算符返回的两个值必须是相同的类型,或者一个必须可以隐式转换为另一个。在这种情况下,null 不能隐式转换为 int,反之亦然,因此需要显式转换。试试这个:
int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));
回答by Will Dean
What Harry S says is exactly right, but
Harry S 说的完全正确,但是
int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));
would also do the trick. (We Resharper users can always spot each other in crowds...)
也会做的伎俩。(我们 Resharper 用户总是可以在人群中发现对方......)
回答by Will Dean
Another option is to use
另一种选择是使用
int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr);
I like this one most.
我最喜欢这个。
回答by tenss
Similarly I did for long:
同样我做了很长时间:
myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;