Parameters 在Visual Basic VB.Net 2010中使用System.DateTime类型作为可选参数

Parameters 在Visual Basic VB.Net 2010中使用System.DateTime类型作为可选参数,parameters,constructor,vb.net-2010,default-value,optional,Parameters,Constructor,Vb.net 2010,Default Value,Optional,我试图将可选的System.DateTime参数传递给VB.NET 2010中的构造函数 ... Public Sub New(Optional ByVal givendate As System.DateTime = System.DateTime.MinValue) ... 我得到一个错误“Konstanter Ausdruck erforderlich”转换为“需要常量值”。我尝试用MinValue填充变量,但我必须使该变量为只读,这导致在尝试将默认值传递给可选参数时出现完全相同

我试图将可选的System.DateTime参数传递给VB.NET 2010中的构造函数

...
Public Sub New(Optional ByVal givendate As System.DateTime = System.DateTime.MinValue)
    ...
我得到一个错误“Konstanter Ausdruck erforderlich”转换为“需要常量值”。我尝试用MinValue填充变量,但我必须使该变量为只读,这导致在尝试将默认值传递给可选参数时出现完全相同的问题。 是否有方法将MinValue作为默认值传递给可选的DateTime(实际上是一种日期类型)。
感谢您的听众。

与此同时,我找到了一个解决方案(感谢vbdotnetformums.com上的同事,所以我想分享一下结果:

第一种可能的解决方案是将参数定义为Object,将默认值定义为Nothing,然后强制转换DateTime

第二个更干净的解决方案(也是我遵循的)是重载构造函数

以下是IanRyder(vbdotnetforums.com)的解决方案:

然后我就能意识到我想要的行为:

Dim myVariable As New MyClassExample

Dim myVariable As New MyClassExample(DateTime.Today.AddDays(-1))

它完全按照我想要的方式工作。我希望有一天其他人会从中获益。

您可以不设置函数参数的默认值,然后在函数中设置今天的日期时间

Public Sub New(Optional ByVal fDate As System.DateTime = Nothing)
        If fDate = Nothing Then
            fDate = Now
        End If
    End Sub
Public Sub New(Optional ByVal fDate As System.DateTime = Nothing)
        If fDate = Nothing Then
            fDate = Now
        End If
    End Sub