C # 为什么不能将一个可空的 int 赋值为 null

解释为什么一个可以为空的 int 不能被赋值为 null

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

密码有什么问题吗?

138726 次浏览

问题不是 null 不能赋值给 int 吗?.问题是三元运算符返回的两个值必须是相同的类型,或者其中一个必须隐式转换为另一个。在这种情况下,null 不能隐式转换为 int 或 Vice-v. ,因此需要显式强制转换。试试这个:

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;