上一个问题:
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)));
[我现在对GetDateTime
和GetInt32
有类似的问题,例如:
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
。
我将如何解决此问题?
您在某处缺少右括号。
DateTime
是struct
,因此是值类型,不能为null
。只有引用类型和Nullable<T>
(或T?
)类型可以为空。您必须使用Nullable<DateTime>
。也可以写为DateTime?
。