[vb.net] ‘DateTime’이 ‘Nothing’인지 왜 확인할 수 없습니까?

VB.NET에서 DateTime변수를 “설정되지 않음” 으로 설정하는 방법이 있습니까? 그리고 a 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.Net, IMO와 혼동의 가장 큰 원인 중 하나입니다.

NothingVB.Net default(T)에서는 주어진 형식의 기본값 인 C # 과 동일 합니다.

  • 값 유형의 경우 기본적으로 ‘0’과 동일합니다. 0for Integer, Falsefor Boolean, DateTime.MinValuefor DateTime, …
  • 참조 유형의 경우 null값입니다 (아무것도 참조하지 않는 참조).

따라서 명령문 d Is Nothingd Is DateTime.MinValue분명히 컴파일되지 않는와 동일합니다.

솔루션 : 다른 사람들이 말했듯이

  • 사용 DateTime?(예 🙂 Nullable(Of DateTime). 이것이 제가 선호하는 솔루션입니다.
  • 또는 사용 d = DateTime.MinValue하거나 동등하게d = Nothing

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

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

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


답변

DateTime은 값 유형이므로 null이 될 수 없습니다. 과 같은지 확인 DateTime.MinValue하거나 Nullable(Of DateTime)대신 사용할 수 있습니다 .

VB는 때때로 “도움이되는”일이 아닌 일을하고 있다고 생각하게 만듭니다. Date를 Nothing으로 설정하면 실제로는 다른 값, 아마도 MinValue로 설정하는 것입니다.

값 유형과 참조 유형에 대한 광범위한 논의는 이 질문 을 참조하십시오 .


답변

DateTime은 값 유형 이며 항상 값이 있음을 의미합니다.

정수와 같습니다. 0, 1 또는 0보다 작을 수 있지만 “아무것도”일 수는 없습니다.

Nothing 값을 취할 수있는 DateTime을 원하는 경우 Nullable DateTime을 사용하십시오.


답변

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 인지 여부를 확인하는 방법 ( Nothing (Visual Basic)에서 ) :

기준 (또는 널 값 유형)이 가변인지 여부를 확인하면 널이 , 사용하지 않는 = 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

수업 종료

‘Main () :

        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