141

解释为什么不能为可为空的 int 分配 null 的值,例如

int? accom = (accomStr == "noval" ? null  : Convert.ToInt32(accomStr));

那个代码有什么问题?

4

4 回答 4

276

问题不在于 null 不能分配给 int 吗?问题是三元运算符返回的两个值必须是同一类型,或者一个必须隐式转换为另一个。在这种情况下,null 不能隐式转换为 int,反之亦然,因此需要显式转换。试试这个:

int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));
于 2008-12-01T10:41:02.303 回答
47

Harry S 说的完全正确,但是

int? accom = (accomStr == "noval" ? null : (int?)Convert.ToInt32(accomStr));

也可以解决问题。(我们 Resharper 用户总是可以在人群中发现彼此......)

于 2008-12-01T10:44:11.877 回答
6

另一种选择是使用

int? accom = (accomStr == "noval" ? Convert.DBNull : Convert.ToInt32(accomStr); 

我最喜欢这个。

于 2010-09-24T06:21:45.400 回答
1

同样,我做了很长时间:

myLongVariable = (!string.IsNullOrEmpty(cbLong.SelectedItem.Value)) ? Convert.ToInt64(cbLong.SelectedItem.Value) : (long?)null;
于 2012-04-09T11:47:46.357 回答