使用通用类型和空运算符时,我遇到一些奇怪的行为。为什么 obj2.CurrentDate 返回的日期值在使用时看起来不正确? (简写)。如果我在属性中长期使用 null 运算符 (if),那么它会返回正确的预期值。我以为?相当于 if(表达式, returnIfTrue, returnIfFalse)。
此外,如果删除泛型类型构造函数,则 null 运算符将按预期工作。为什么是这样?
Return If(CurrentObject1 IsNot Nothing, CurrentObject1.MyDate, Nothing) -- Long Hand Returns correct value
Return CurrentObject1?.MyDate --Short Hande - Returns incorrect value
第一个控制台应用程序 - 使用通用类型构造函数,CurrentDate 不是预期的。
Module Module1
Sub Main()
Dim obj1 As New MyObject1 With {.MyDate = CDate("2017-11-13T14:25:00Z")}
Dim obj2 As New MyObject2(Of MyObject1)(obj1)
Console.WriteLine(obj1.MyDate)
Console.WriteLine(obj2.CurrentDate)
Console.ReadKey()
End Sub
End Module
Public MustInherit Class MyBaseObject1
Property MyDate As Date
End Class
Public Class MyObject1
Inherits MyBaseObject1
End Class
Public Class MyObject2(Of MyObjectType As {MyBaseObject1, New})
Public Sub New(obj As MyObjectType)
m_CurrentObject1 = obj
End Sub
Private m_CurrentObject1 As MyObjectType = Nothing
Public ReadOnly Property CurrentObject1 As MyObjectType
Get
Return m_CurrentObject1
End Get
End Property
Public ReadOnly Property CurrentDate As Date?
Get
Return CurrentObject1?.MyDate
End Get
End Property
End Class
控制台应用程序 1 的输出
2017 年 11 月 13 日 8:25:00 上午
2/24/0010 4:56:53 上午
第二个控制台应用程序 - 没有泛型类型构造函数。按预期工作
Module Module1
Sub Main()
Dim obj1 As New MyObject1 With {.MyDate = CDate("2017-11-13T14:25:00Z")}
Dim obj2 As New MyObject2(obj1)
Console.WriteLine(obj1.MyDate)
Console.WriteLine(obj2.CurrentDate)
Console.ReadKey()
End Sub
End Module
Public MustInherit Class MyBaseObject1
Property MyDate As Date
End Class
Public Class MyObject1
Inherits MyBaseObject1
End Class
Public Class MyObject2
Public Sub New(obj As MyBaseObject1)
m_CurrentObject1 = obj
End Sub
Private m_CurrentObject1 As MyBaseObject1 = Nothing
Public ReadOnly Property CurrentObject1 As MyBaseObject1
Get
Return m_CurrentObject1
End Get
End Property
Public ReadOnly Property CurrentDate As Date?
Get
Return CurrentObject1?.MyDate
End Get
End Property
End Class
第二个控制台应用程序的输出
2017 年 11 月 13 日 8:25:00 上午
2017 年 11 月 13 日 8:25:00 上午