일반 유형 및 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
첫 번째 콘솔 응용 프로그램 - 일반 형식 생성자를 사용하면 CurrentDate가 예상과 다릅니다. 콘솔 응용 프로그램 1
2017년 11월 13일 오전 8시 25분 0초
2/24/0010 오전 4시 56분 53초
2 콘솔 응용 프로그램의
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
출력 - 제네릭 형식 생성자가 없습니다. 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분 0초
2017년 11월 13일 오전 8시 25분 0초
질문에 출력하는 값을 편집해야합니다. 그러면 다른 사람의 관심을 부추길 가능성이 커집니다. 표시된대로 코드가 "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? '가 아닙니다. –
See [반환되는 'IF()'의 형식에 대해 질문하는 비슷한 코드입니다 (https://stackoverflow.com/a/12595889/15498) –