ジェネリック型とnull演算子を使用するときに私はいくつかの奇妙な動作が発生しています。なぜobj2.CurrentDateは?を使用すると正しくないと思われる日付値を返しますか? (短い手)。プロパティでnull演算子(if)を手近に渡すと、正しい値と期待値が返されます。私は思った? if(expression、returnIfTrue、returnIfFalse)と等価でした。Null(?)演算子は、ジェネリック型コンストラクタを使用しているときに不正な値を返します。 VB.NET
また、ジェネリック型コンストラクタが削除されると、null演算子は期待どおりに動作します。どうしてこれなの?
Return If(CurrentObject1 IsNot Nothing, CurrentObject1.MyDate, Nothing) -- Long Hand Returns correct value
Return CurrentObject1?.MyDate --Short Hande - Returns incorrect value
第1コンソールアプリケーション - Generic Typeコンストラクタでは、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秒AM
2/24/0010午前4時56分53秒AM
2コンソールアプリケーションの出力 - ジェネリック型コンストラクタなし。
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秒AM
2017年11月13日午前8時25分00秒AM
質問に出力する値を編集する必要があります。私は "24/02/0010 04:56:53"と表示されているコードを使用しています。もし私が 'Property MyDate As Date ?'を使用した場合、私は" 01/01/0001 00:28:38 "を取得します。 –
VBの 'Nothing'は' null'よりもC#の 'default(T)'に似ています。したがって、たとえば、最初の式の* type *は 'Date'、*ではなく' Date? 'です。 –
参照[IF()の戻り値の型について尋ねる似たようなコードです](https://stackoverflow.com/a/12595889/15498) –