int 和 null 之间没有隐式转换
No implicit conversion between int and null
我有一个 class,它具有如下所示的可为 null 的属性;
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);
}
它给出类似 "Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and ''" 的错误。
null 没有任何可识别的类型 - 它只需要一点点刺激就可以让它开心:示例如下所示。
int? number = true ? 5 : (int?)null;
或者你可以
int? number = true ? 5 : null as int?;
我有一个 class,它具有如下所示的可为 null 的属性;
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);
}
它给出类似 "Type of conditional expression cannot be determined because there is no implicit conversion between 'int' and ''" 的错误。
null 没有任何可识别的类型 - 它只需要一点点刺激就可以让它开心:示例如下所示。
int? number = true ? 5 : (int?)null;
或者你可以
int? number = true ? 5 : null as int?;