【问题标题】:Getting "no implicit conversion between '<null>' and 'System.DateTime'" error message [closed]获取“'<null>' 和 'System.DateTime' 之间没有隐式转换”错误消息 [关闭]
【发布时间】:2012-03-13 00:45:48
【问题描述】:

在上一个问题中:

Getting "This method or property cannot be called on Null values" error

以下代码有问题:

client_group_details.Add(new ClientGroupDetails(
    reader.GetString(Col2Index),
    reader.GetString(Col3Index)));

我在哪里得到以下错误:

Data is Null. This method or property cannot be called on Null values.

使用以下代码解决了这个问题:

client_group_details.Add(new ClientGroupDetails(
    reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
    reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index)));

我现在对GetDateTimeGetInt32 也有类似的问题,例如:

client_group_details.Add(new ClientGroupDetails(
    reader.GetString(Col2Index),
    reader.GetString(Col3Index),
    reader.GetDateTime(Col4Index)));

我尝试使用以下方法解决此问题,但没有成功

client_group_details.Add(new ClientGroupDetails(
    reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
    reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index),
    reader.IsDbNull(Col2Index) ? null : reader.GetDateTime(Col4Index)));

它给出了错误:

Compiler Error Message: CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between '<null>' and 'System.DateTime'

搜索解决方案后,发现:Nullable type issue with ?: Conditional Operator。但是当我尝试使用该代码时,我不断收到) expected

我该如何解决这个问题?

【问题讨论】:

  • 计算你的括号。你的左括号比右括号多。
  • 发布您尝试使用的导致) expected 错误的代码。这是一个简单的语法错误,应该很容易修复。
  • 感谢 John Saunders 指出我完全没有抓住重点。答案已删除。
  • 20 小时,仍然没有代码的迹象与括号的实际问题。结束也不是一个真正的问题。

标签: c# .net-3.5 c#-3.0 asmx asp.net-3.5


【解决方案1】:

DateTimestruct,因此是值类型,不能是 null。只有引用类型和Nullable&lt;T&gt;(或T?)类型可以为空。您必须使用Nullable&lt;DateTime&gt;。这也可以写成DateTime?

DateTime? dt = null;
dt = DateTime.Now;
if (dt.HasValue) ...
if (dt == null) ...
DateTime x = dt.Value;

dt = reader.IsDBNull(Col2Index) ? (DateTime?)null : reader.GetDateTime(Col4Index);

【讨论】:

  • 这就是我一直在尝试的,但我不断收到) expected
  • 尝试使用reader.IsDBNull(Col2Index) ? (DateTime?)null : reader.GetDateTime(Col4Index)。三元运算符很混乱,因为它无法确定null的类型。
  • 您在某处出现语法错误。你的() 多。尝试在末尾添加)
  • @oshirowanen 发布引发) expected 错误的代码。 在末尾添加) 可能会也可能不会解决问题。
【解决方案2】:

您在某处缺少右括号。

client_group_details.Add(new ClientGroupDetails(
    reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
    reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index),
    reader.IsDbNull(Col2Index) ? null : reader.GetDateTime(Col4Index)));

应该改成

client_group_details.Add(new ClientGroupDetails(
    reader.IsDbNull(Col2Index) ? null : reader.GetString(Col2Index),
    reader.IsDbNull(Col3Index) ? null : reader.GetString(Col3Index),
    reader.IsDbNull(Col2Index) ? (DateTime?)null : reader.GetDateTime(Col4Index)));

或类似的东西。根据您的确切代码,有人将能够告诉您缺少的括号在哪里。

【讨论】:

    猜你喜欢
    • 2013-09-01
    • 2016-06-24
    • 2013-12-22
    • 2015-07-14
    • 2018-03-14
    • 1970-01-01
    • 2023-03-17
    • 2015-11-25
    • 1970-01-01
    相关资源
    最近更新 更多