source

'날짜 시간'이 '없음'인지 확인할 수 없는 이유는 무엇입니까?

manysource 2023. 6. 4. 10:37

'날짜 시간'이 '없음'인지 확인할 수 없는 이유는 무엇입니까?

VB.NET에서 다음을 설정할 수 있는 방법이 있습니까?DateTime변수에서 "설정 안 함"으로?그리고 왜 설정이 가능합니까?DateTime로.Nothing그러나 그것이 맞는지 확인할 수 없습니다.Nothing예:

Dim d As DateTime = Nothing
Dim boolNotSet As Boolean = d Is Nothing 

두 번째 문은 다음 오류를 발생시킵니다.

'Is' operator does not accept operands of type 'Date'. Operands must be reference or
nullable types.

이것은 VB와의 가장 큰 혼동의 원인 중 하나입니다.네트, IMO.

NothingVB에서 Net은 다음과 같습니다.defaultC#: 지정된 유형의 기본값입니다.

  • 값 유형의 경우 이 값은 기본적으로 '0'과 같습니다.0위해서Integer,False위해서Boolean,DateTime.MinValue위해서DateTime, ...
  • 참조 유형의 경우 다음과 같습니다.nullvalue(아무것도 언급하지 않는 참조).

진술서d Is Nothing따라서 와 동등합니다.d Is DateTime.MinValue분명히 컴파일이 되지 않습니다.

해결책: 다른 사람들이 말했듯이

  • 둘 중 하나 사용DateTime?(즉,Nullable(Of DateTime)) 이것이 제가 선호하는 해결책입니다.
  • 또는 사용d = DateTime.MinValue또는 동등하게d = Nothing

원래 코드의 맥락에서 다음을 사용할 수 있습니다.

Dim d As DateTime? = Nothing
Dim boolNotSet As Boolean = Not d.HasValue

더 포괄적인 설명은 Anthony D에서 찾을 수 있습니다. 그린의 블로그

DateTime은 값 형식이므로 null일 수 없습니다.다음과 동일한지 확인할 수 있습니다.DateTime.MinValue또는 사용할 수 있습니다.Nullable(Of DateTime)대신.

VB는 때때로 "도움이 되는" 것이 아닌 것을 하고 있다고 생각하게 만듭니다.날짜를 [없음]으로 설정할 수 있는 경우 다른 값(최소 값)으로 설정합니다.

값 유형 대 참조 유형에 대한 자세한 내용은 이 질문을 참조하십시오.

DateTime은 유형입니다. 즉, 항상 일부 값을 가집니다.

이것은 정수와 같습니다. 0, 1 또는 0보다 작을 수 있지만 "아무것도" 될 수 없습니다.

없음 값을 사용할 수 있는 DateTime을 사용하려면 NullableDateTime을 사용합니다.

nullable 작업에 대한 몇 가지 예DateTime가치.

(자세한 내용은 Nullable 값 유형(Visual Basic)을 참조하십시오.)

'
' An ordinary DateTime declaration. It is *not* nullable. Setting it to
' 'Nothing' actually results in a non-null value.
'
Dim d1 As DateTime = Nothing
Console.WriteLine(String.Format("d1 = [{0}]\n", d1))
' Output:  d1 = [1/1/0001 12:00:00 AM]

' Console.WriteLine(String.Format("d1 is Nothing? [{0}]\n", (d1 Is Nothing)))
'
'   Compilation error on above expression '(d1 Is Nothing)':
'
'      'Is' operator does not accept operands of type 'Date'.
'       Operands must be reference or nullable types.

'
' Three different but equivalent ways to declare a DateTime
' nullable:
'
Dim d2? As DateTime = Nothing
Console.WriteLine(String.Format("d2 = [{0}][{1}]\n", d2, (d2 Is Nothing)))
' Output:  d2 = [][True]

Dim d3 As DateTime? = Nothing
Console.WriteLine(String.Format("d3 = [{0}][{1}]\n", d3, (d3 Is Nothing)))
' Output:  d3 = [][True]

Dim d4 As Nullable(Of DateTime) = Nothing
Console.WriteLine(String.Format("d4 = [{0}][{1}]\n", d4, (d4 Is Nothing)))
' Output:  d4 = [][True]

또한 변수가 null인지 확인하는 방법(없음(Visual Basic)에서):

기준(또는 null 가능한 값 유형) 변수가 다음과 같은지 확인할 수 있습니다.null, 사용 안 함 = Nothing또는 <> Nothing항상 사용 Is Nothing또는 IsNot Nothing.

모든 프로그래밍 언어에서 Null을 사용할 때는 주의해야 합니다.위의 예는 다른 문제를 보여줍니다.Nullable 유형을 사용하면 해당 유형에서 인스턴스화된 변수가 System 값을 유지할 수 있음을 의미합니다.DBNull.Value. "= Nothing"을 사용하여 값을 기본값으로 설정하는 해석을 변경했거나 값의 Object가 null 참조를 지원할 수 있는 것은 아닙니다.그냥 경고야...해피 코딩!

값 유형을 포함하는 별도의 클래스를 만들 수 있습니다.이러한 클래스에서 생성된 개체는 Nothing(없음)으로 할당될 수 있는 참조 유형입니다.예:

Public Class DateTimeNullable
Private _value As DateTime

'properties
Public Property Value() As DateTime
    Get
        Return _value
    End Get
    Set(ByVal value As DateTime)
        _value = value
    End Set
End Property

'constructors
Public Sub New()
    Value = DateTime.MinValue
End Sub

Public Sub New(ByVal dt As DateTime)
    Value = dt
End Sub

'overridables
Public Overrides Function ToString() As String
    Return Value.ToString()
End Function

클래스 종료

'주():

        Dim dtn As DateTimeNullable = Nothing
    Dim strTest1 As String = "Falied"
    Dim strTest2 As String = "Failed"
    If dtn Is Nothing Then strTest1 = "Succeeded"

    dtn = New DateTimeNullable(DateTime.Now)
    If dtn Is Nothing Then strTest2 = "Succeeded"

    Console.WriteLine("test1: " & strTest1)
    Console.WriteLine("test2: " & strTest2)
    Console.WriteLine(".ToString() = " & dtn.ToString())
    Console.WriteLine(".Value.ToString() = " & dtn.Value.ToString())

    Console.ReadKey()

    ' Output:
    'test1:  Succeeded()
    'test2:  Failed()
    '.ToString() = 4/10/2012 11:28:10 AM
    '.Value.ToString() = 4/10/2012 11:28:10 AM

그런 다음 재정의 대상을 선택하여 필요한 작업을 수행할 수 있습니다.많은 일이 있습니다. 하지만 정말로 필요하다면 할 수 있습니다.

아래를 간단하게 사용하여 확인할 수도 있습니다.

If startDate <> Nothing Then
your logic
End If

DateTime 데이터 유형의 startDate 변수가 null인지 확인합니다.

아래와 같이 확인할 수 있습니다.

if varDate = "#01/01/0001#" then
       '  blank date. do something.
else
       ' Date is not blank. Do some other thing
end if

이 문제를 해결하는 방법은 객체 데이터 유형을 대신 사용하는 것입니다.

Private _myDate As Object
Private Property MyDate As Date
    Get
        If IsNothing(_myDate) Then Return Nothing
        Return CDate(_myDate)
    End Get
    Set(value As Date)
        If date = Nothing Then
            _myDate = Nothing
            Return
        End If
        _myDate = value
     End Set
End Property

그런 다음 날짜를 다음과 같이 설정할 수 있습니다.

MyDate = Nothing
Dim theDate As Date = MyDate
If theDate = Nothing Then
    'date is nothing
End If

언급URL : https://stackoverflow.com/questions/5869661/why-cant-i-check-if-a-datetime-is-nothing