【问题标题】:CS0173 C# Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'CS0173 C# 条件表达式的类型无法确定,因为 'System.DateTime' 和 'System.DBNull' 之间没有隐式转换
【发布时间】:2018-09-27 22:18:25
【问题描述】:

我有一个 MS SQL 本地数据库,它允许列字段具有空值。但是,当我尝试将 (DateTime?) 字段设置为 null 时,出现异常“System.ArgumentException 无法将列 'DeliveryTime' 设置为 null。请改用 DBNull。”。所以我尝试将 (DateTime?) null 替换为 DBNull.value。然后弹出编译错误

"CS0173 C# 条件表达式类型无法确定 因为 'System.DateTime' 和 'System.DBNull'"

我正在使用 MS VS 2017 社区。我该怎么办?

DataRow row; 
string rs; 
DateTime dt; 

row["DeliveryTime"] = DateTime.TryParse(rs, out dt) ? dt : (DateTime?) null;
// I replaced (DateTime?) null to DBNull.Value and got a compile error

【问题讨论】:

  • 请向我们展示您设置这些值的代码。
  • 请发布您的代码和更多详细信息。
  • DataRow 行;字符串 rs;日期时间 dt; row["DeliveryTime"] = DateTime.TryParse(rs, out dt) ? dt:(日期时间?)空; // 我将 (DateTime?) null 替换为 DBNull.Value 并得到一个编译错误

标签: c# dbnull


【解决方案1】:

听起来你正在做(在分配或调用中 - 基本上是某种表达):

val == null ? DBNull.Value : val.Value

或类似的东西;问题是条件运算符的两个结果需要有一个共同的类型。这里最简单的解决方法是

((object)val) ?? DBNull.Value

这使用了空合并,并且没有值的 Nullable<T> 将转换为 null 引用。

【讨论】:

    猜你喜欢
    • 2018-03-14
    • 2013-08-18
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-08
    相关资源
    最近更新 更多