2013-01-11 24 views
6

我有兩個問題:日期時間在VB.NET和C#

  1. DateDateTime:他們是在VB不同或相同?

  2. DateTime可以在VB中分配Nothing,因爲它不能在C#中分配爲null。作爲一個結構,它不能爲空。那麼爲什麼在VB中允許它?

--- ----- VB.NET

Module Module1 

    Sub Main() 
     Dim d As Date = Nothing 
     Dim dt As DateTime = Nothing 

     d = CType(MyDate, DateTime) 


    End Sub 

    Public ReadOnly Property MyDate As DateTime 
     Get 
      Return Nothing 
     End Get 
    End Property 

End Module 

--- C#的.NET -----

class Program 
    { 
     static void Main(string[] args) 
     { 
      DateTime dt = null;//compile time error    
     } 
    } 
+0

查看http://stackoverflow.com/questions/798121/date-vs-datetime – Steve

+1

@musefan:好的,但在VB.NET中,你可以寫Dim Dim As Date? =無「。那有什麼區別? –

+0

@TimSchmelter:非常恰當的命名「暗淡」是不同的。我知道我們很酷的孩子有一個懶惰的'變種',但我對VB的盲目仇恨不需要有理由支持,我只需要確保我盡我所能,並在有機會出現時做出正確的噪音。 .. #CutForVB – musefan

回答

13

在VB.NET Nothing不與C#中的null相同。它還具有C#中default的功能,當您在像System.DateTime這樣的結構上使用它時會發生這種情況。

所以兩者DateDateTime指代相同的結構System.DateTime

Dim dt As Date = Nothing 

實際上是相同的

Dim dt = Date.MinValue 

或(在C#)

DateTime dt = default(DateTime); 
+1

是的,向後兼容是一個婊子... :-( –

+0

我總是覺得它很有趣,當人們說'爲什麼這些語言不相同!'的想法是,如果他們是相同的唯一的區別將最終成爲你用它來做的話...... – RhysW

+1

+1不知道什麼都不是null –

3

在C#您可以使用default關鍵字

DateTime dt = default(DateTime); 

DateDateTime在VB.NET中是一樣的。 Date只是DateTime

3

在vb.net Datealias簡直是DateTime一個alias

VB中存在的一些別名用於遺留目的,以幫助從vb6應用程序進行轉換。