使用Generic Types和null运算符时,我遇到了一些奇怪的行为。为什么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的输出
11/13/2017 8:25:00 AM
2/24/0010 4:56:53 AM
第二个控制台应用程序 - 没有泛型类型构造函数。按预期工作
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
第二个控制台应用程序的输出
11/13/2017 8:25:00 AM
11/13/2017 8:25:00 AM
答案 0 :(得分:1)
是的,这看起来像编译器错误。马上解决它。在此期间,您可以使用以下解决方法: DirectCast(CurrentObject1,MyBaseObject1)?. MyDate