解释为什么不能为可为空的 int 分配 null 的值,例如
int? accom = (accomStr == "noval" ? null : Convert.ToInt32(accomStr));
那个代码有什么问题?
问题不在于 null 不能分配给 int 吗?问题是三元运算符返回的两个值必须是同一类型,或者一个必须隐式转换为另一个。在这种情况下,null 不能隐式转换为 int,反之亦然,因此需要显式转换。试试这个:
int? accom = (accomStr == "noval" ? (int?)null : Convert.ToInt32(accomStr));
Harry S 说的完全正确,但是
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;