2011-05-03 3 views
63

VB.NET에서 DateTime 변수를 "설정하지 않음"으로 설정하는 방법이 있습니까? 그리고 DateTimeNothing으로 설정할 수있는 이유는 무엇입니까? 이 아닌 Nothing인지 확인하려면이 가능합니까? 예를 들어 :왜 'DateTime'이 '아무것도'아닌지 확인할 수 있습니까?

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. 
+1

아래의 John Gant의 답변 외에도 datetime 변수 = Nothing인지 확인해 볼 수 있습니다 ("is"대신에 = 참고). – NYSystemsAnalyst

+0

감사합니다, Dim boolNotSet As Boolean = d = 아무것도 가장 간단한 해결책처럼 보이지 않습니다. – Muleskinner

+0

@Chris - 그가 VB를 사용하고 있다고 생각합니다. –

답변

117

이것은 VB.Net, IMO와의 가장 큰 혼란의 하나입니다.

Nothing (VB.Net)은(C#에서는 해당 유형의 기본값)에 해당합니다.

치형
  • 이 본질적으로 "제로"의 등가물이다 Integer위한 0, Boolean위한 False, DateTime위한 DateTime.MinValue ...
  • 기준 유형의
  • 은 그것이 null 값 (기준 인 그 말은, 음, 아무것도).

따라서 d Is Nothing은 분명히 컴파일되지 않는 d Is DateTime.MinValue과 같습니다.

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

  • 중 하나가 DateTime? (즉 Nullable(Of DateTime))를 사용합니다. 이것이 내가 선호하는 해결책이다.
  • 또는 사용 d = DateTime.MinValue 또는 원래 코드의 맥락에서 동등하게 d = Nothing

, 당신은 사용할 수 있습니다 : 널 (null)을 사용하는 경우

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

날짜 시간 그것이 null 일 수 없습니다 이유는 값 형식입니다. 이 파일이 DateTime.MinValue과 같은지 확인하거나 Nullable(Of DateTime)을 대신 사용할 수 있습니다.

VB는 때로는 "도움이된다"는 생각을하게 만들어줍니다. Date to Nothing을 설정할 수있게되면 실제로 다른 값, 아마도 MinValue로 설정됩니다.

값 유형 대 참조 유형에 대한 자세한 설명은 this question을 참조하십시오.

2

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

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

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

1

을 모든 프로그래밍 언어에주의해야합니다. 위의 예는 다른 문제를 보여줍니다. Nullable 형식을 사용하면 해당 형식에서 인스턴스화 된 변수가 System.DBNull 값을 보유 할 수 있음을 의미합니다.값; "= 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 

그런 다음 당신이 선택하고 당신이 무엇을해야 할 overridables를 선택할 수 있습니다. 일이 많지만, 정말로 필요하다면 할 수 있습니다.

3

nullable DateTime 값으로 작업하는 몇 가지 예제입니다.

(이상 Nullable Value Types (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] 

또한, 변수가 (Nothing (Visual Basic)에서) 여부를 확인하는 방법에 대한 :하는 것이 주위

When checking whether a reference (or nullable value type) variable is null, do not use = Nothing or <> Nothing . Always use Is Nothing or IsNot Nothing .
0

있는 방법 대신 Object 데이터 유형을 사용하십시오.

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 
1
또한 확인하는 단순한 이하로 사용할 수 있습니다

:

If startDate <> Nothing Then 
your logic 
End If 
그것은 날짜 시간 데이터 형식의의 startDate 변수가 null 여부를 확인합니다

.

관련 문제