无法将 int 转换为可为 null 的 int

Cannot convert int to nullable int

在我的 C# 应用程序中,我想将空值存储在一个对象中,例如:

if (txtClass8Year.Text == "")
{
    distributor.Class8YrPassing = null;
}
else
{
    distributor.Class8YrPassing = Convert.ToInt32(txtClass8Year.Text);
}

但是当我试图在一行中写下整个语句时它不起作用:

(txtClass8Year.Text == "") ? null : Convert.ToInt32(txtClass8Year.Text);

提前致谢。

帕萨

您需要将 int 结果转换回 Nullable<int>,因为 intint? 的类型不同,它们不能隐式转换为来自,所以我们需要具体说明:

distributor.Class8YrPassing = (txtClass8Year.Text == "") 
                               ? null 
                               : (int?)Convert.ToInt32(txtClass8Year.Text);

或者您可以将 null 强制转换为 int? 也可以:

distributor.Class8YrPassing = (txtClass8Year.Text == "") 
                               ? (int?)null 
                               : Convert.ToInt32(txtClass8Year.Text);

至于三元运算符,我们需要确保在两种情况下都返回相同的类型,否则编译器会给出上述错误。

一个建议是使用 String.IsNullOrEmpty 方法而不是检查 "" 文字字符串更好:

distributor.Class8YrPassing = String.IsNullOrEmpty(txtClass8Year.Text) || String.IsNullOrWhiteSpace(txtClass8Year.Text)
                               ? null 
                               : (int?)Convert.ToInt32(txtClass8Year.Text);