【问题标题】:Why inline if produces different result than normal if? [duplicate]为什么内联 if 会产生与正常 if 不同的结果? [复制]
【发布时间】:2026-01-08 06:15:01
【问题描述】:

假设 exp.Row.IsdeliveryDateNull() 返回 True。
拥有此代码:

Dim theDate As Date?

If exp.Row.IsdeliveryDateNull() Then
    theDate = Nothing
Else
    theDate = exp.Row.deliveryDate
End If
' Result: theDate = Nothing

theDate = If(exp.Row.IsdeliveryDateNull(), Nothing, exp.Row.deliveryDate)
' Result: theDate = is #1/1/0001 12:00:00 AM# (Default value of Date)

为什么 theDate 会根据 if 的类型(普通或内联)获得不同的值?
我期待theDate = Nothing 两种方式。

我发现了类似的问题: Why C# inline if result is different than if?

【问题讨论】:

  • 您在上面提供的代码对我来说看起来不错。请提供minimal reproducible example
  • 如果您将内联版本中的Nothing 更改为DirectCast(Nothing, Date?),它会做您想要的吗?否则,请告诉我们你得到了什么值。
  • 对不起@Igor,我以为会很清楚。
  • @VisualVincent,除此之外,人们希望能够帮助执行网站的重复政策,但要回答这个问题。如果可以链接到他们以前的答案之一,那就更好了。

标签: .net vb.net


【解决方案1】:

If 运算符永远不会将Nothing 解释为可空值类型,除非其他可能的返回类型也是可空值类型。如果该值是常规值类型,则 Nothing 将始终被解释为该类型的默认值。要使If 的返回类型为Date?,那么至少一个可能的返回值实际上必须明确地是Date?

theDate = If(exp.Row.IsdeliveryDateNull(), Nothing, New Date?(exp.Row.deliveryDate))

或:

theDate = If(exp.Row.IsdeliveryDateNull(), DirectCast(Nothing, Date?), exp.Row.deliveryDate)

【讨论】:

  • 很好的解释@jmcilhinney。因此,如果 exp.Row.deliveryDate 的类型为 Date? 而不是 Date,则内联 if 将产生 Date??
  • 理论上是的,但是类型化的DataRow 的属性永远不能是可为空的值类型。如果可以,那么就不需要那些IsXyzNull 方法。整个问题源于 ADO.NET 起源于可空值类型之前的时间,因此他们选择使用特定类型 - DBNull - 来表示数据库空值。这是因为,虽然Nothing 不能代表引用类型的值,但它不能代表值类型。现在可以了,为时已晚。像 Entity Framework 这样的东西没有这个问题,尽管它仍然使用 ADO.NET。
最近更新 更多