C# 代码不会编译。null 和 int 之间没有隐式转换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1279046/
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# code won't compile. No implicit conversion between null and int
提问by Hcabnettek
Possible Duplicate:
Nullable types and the ternary operator: why is `? 10 : null` forbidden?
Why doesn't this work? Seems like valid code.
为什么这不起作用?似乎是有效的代码。
string cert = ddCovCert.SelectedValue;
int? x = (string.IsNullOrEmpty(cert)) ? null: int.Parse(cert);
Display(x);
How should I code this? The method takes a Nullable. If the drop down has a string selected I need to parse that into an int otherwise I want to pass null to the method.
我应该如何编码?该方法采用 Nullable。如果下拉选择了一个字符串,我需要将其解析为 int 否则我想将 null 传递给该方法。
采纳答案by Mehrdad Afshari
int? x = string.IsNullOrEmpty(cert) ? (int?)null : int.Parse(cert);
回答by Scott Vercuski
I've come across the same thing ... I usually just cast the null to (int?)
我遇到过同样的事情......我通常只是将 null 转换为 (int?)
int? x = (string.IsNullOrEmpty(cert)) ? (int?)null: int.Parse(cert);