得到“没有从'<null>'到'System.DateTime'的隐式转换”错误消息

4

在之前的问题中:

获取“此方法或属性无法在Null值上调用”错误

我遇到了以下代码问题:

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”错误提示。如何解决这个问题呢?

1
数一下你的括号。你有比右括号更多的左括号。 - Eric Lippert
请发布您尝试使用的代码,导致出现“)expected”错误。这是一个简单的语法错误,应该很容易修复。 - phoog
感谢John Saunders指出我完全错了。回答已删除。 - Almo
20个小时过去了,仍然没有找到带有括号实际问题的代码。将其标记为“不是一个真正的问题”。 - Lasse V. Karlsen
2个回答

9

DateTime 是一个struct类型,因此它是值类型,不能为null。只有引用类型和Nullable<T>(或T?)类型可以为null。您需要使用Nullable<DateTime>类型,这也可以写成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”的错误提示。 - oshirowanen
1
尝试使用 reader.IsDBNull(Col2Index) ? (DateTime?)null : reader.GetDateTime(Col4Index)。三元运算符很困惑,因为它无法确定 null 的类型。 - Olivier Jacot-Descombes
你有一个语法错误。你有多余的更多。尝试在末尾添加一个 - Olivier Jacot-Descombes
@oshirowanen 发布引发 ) expected 错误的代码。 在末尾添加 ) 可能会或可能不会解决问题。 - phoog

8
你的某处缺少了一个闭合括号。
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)));

或者类似的错误。根据您的代码,有人会告诉您缺少的括号在哪里。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接