c# - 无法将 int 转换为可空 int

标签 c# asp.net nullable

在我的 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>,因为 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);

关于c# - 无法将 int 转换为可空 int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48850504/

相关文章:

java - fragment 问题中的 NullPointerException

c# - 如何调用需要.Net Core签名的XML SOAP服务?

c# - 如何构造Dictionary <string,List <string >>的实例

c# - 不存在从对象类型 System.Web.UI.WebControls.TextBox 到已知托管提供程序 native 类型的映射

c# - 选择列表返回 System.Data.Entity.DynamixProxies 而不是 MVC asp.net C# 中的值

ios - 非空值作为方法中的返回值不起作用?

c# - JavaScript 中 `?` 存在的意义是什么?

c# - 在每个 C# 应用程序中可以找到哪些信息用作加密的唯一盐?

C# 接口(interface)<T> { T Func<T>(T t);} : Generic Interfaces with Parameterized Methods with Generic Return Types

c# - 循环到 LINQ 转换 -