【问题标题】:DateTime in VB.NET and C#VB.NET 和 C# 中的日期时间
【发布时间】:2013-01-11 15:36:25
【问题描述】:

我有两个问题:

  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            
        }
    }

【问题讨论】:

  • @musefan: 好的,但是在 VB.NET 中你可以写 Dim dt As Date? = Nothing。那么有什么区别呢?
  • @TimSchmelter:非常恰当地命名为Dim 就是区别。我知道我们很酷的孩子有永远懒惰的“var”,但我对 VB 的盲目仇恨不需要有理由支持,我只需要确保我尽我所能,并在机会出现时发出正确的声音。 .. #CutForVB

标签: c# .net vb.net datetime value-type


【解决方案1】:

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);

【讨论】:

  • 当人们说“为什么这些语言不一样!”时,我总是觉得很有趣。如果它们是相同的,那么唯一的区别就是你用来做这件事的词......
【解决方案2】:

在c#中可以使用default关键字

DateTime dt = default(DateTime);

DateDateTime 在 VB.NET 中是相同的。 Date 只是 aliasDateTime

【讨论】:

    【解决方案3】:

    在 vb.net 中,Date 只是 aliasDateTime

    VB 中存在的一些别名用于遗留用途,以帮助从 vb6 应用程序进行转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-14
      • 2017-01-10
      • 2012-11-23
      • 2012-09-02
      相关资源
      最近更新 更多