c# - int 和 null 之间没有隐式转换

标签 c# nullable implicit-conversion

这个问题在这里已经有了答案:





Conditional operator assignment with Nullable<value> types?

(6 个回答)


6年前关闭。




我有一个类,它具有如下所示的可为空属性;

public class Sample
{
   public int? ID { get; set; }
   public string SampleName { get; set; }
   public bool? Active { get; set; }
   public DateTime? Date { get; set; }
}

当我尝试做类似下面的事情时;
foreach (DataRow tableItem in table.Rows)
{
        Sample sample = new Sample()
        {
            ID = tableItem["ID"] != DBNull.Value ? Convert.ToInt32(tableItem["ID"].ToString()) : null,
            SampleName = tableItem["SampleName"] != DBNull.Value ? tableItem["SampleName"].ToString() : null,
            Active = tableItem["Active"] != DBNull.Value ? Convert.ToBoolean(tableItem["Active"].ToString()) : null,
            Date = tableItem["Date"] != DBNull.Value ? Convert.ToDateTime(tableItem["Date"].ToString()) : null,
        };

    data.Add(sample);
}

它给出了诸如“无法确定条件表达式的类型,因为‘int’和‘’之间没有隐式转换”之类的错误。

最佳答案

null 没有任何可识别的类型——它只需要一点刺激就能让它开心:示例如下所示。

int? number = true ? 5 : (int?)null;

或者你可以做
int? number = true ? 5 : null as int?;

关于c# - int 和 null 之间没有隐式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30045129/

相关文章:

c# - 在 IsolatedStorageSettings 中存储对象

Scala:类似 Option (Some, None) 但具有三种状态:Some、None、Unknown

java - Kotlin 的智能转换未能通过简单的不可空性推导

java - 复合分配的自动(取消)装箱失败

c++ - 在返回 shared_ptr 的函数中返回新的东西

c# - 在 SignalR hub 中存储特定客户端的连接 ID

c# - Entity Framework 中主键不递增

c# - 根 Android shell 使用 Runtime().Exec ("command"卡在 ReadLine() 上)

c# - 为什么 Visual Studio 不警告我空引用异常?

c++ - 在 vector 构造函数中从 initializer_list<const char*> 转换为 initializer_list<string>