C#为什么不能为null的INT被赋值为null作为值
问题描述:
解释为什么一个可空INT不能被赋值为null e.g的价值C#为什么不能为null的INT被赋值为null作为值
int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr));
什么是错的代码?
答
问题不在于null无法分配给int ?.问题是三元运算符返回的两个值必须是相同的类型,否则必须隐式转换为另一个。在这种情况下,null不能隐式地转换为int,也不能使用,因此必须使用explict转换。试试这个:
int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));
答
哈里说什么是完全正确的,但
int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));
也将这样的伎俩。 (我们ReSharper的用户可随时抽查彼此在人群中...)
答
另一种选择是使用
int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr);
我喜欢这一张最。
答
同样我也为长:
myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;
这很有趣 - 你实际上并不需要的塑像为Convert.ToInt32 ... – 2008-12-01 10:44:38
这是因为System.Int32 = System.Nullable –
2008-12-01 10:59:58
为什么长! ?工作没有演员? – 2010-05-27 13:49:07