在我的 C# 应用程序中,我想将 null 值存储在对象中,例如:
if (txtClass8Year.Text == "")
{
distributor.Class8YrPassing = null;
}
else
{
distributor.Class8YrPassing = Convert.ToInt32(txtClass8Year.Text);
}
但是当我尝试将整个语句写在一行中时它不起作用:
(txtClass8Year.Text == "") ? null : Convert.ToInt32(txtClass8Year.Text);
提前致谢。
帕萨
最佳答案
您需要将 int
结果转换回 Nullable<int>
,因为 int
与 int?
的类型不同,并且它们不能隐式转换,因此我们需要具体说明:
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);
关于c# - 无法将 int 转换为可空 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48850504/