![](/img/trans.png)
[英]“Property 'System.DateTime Date' is not defined for type 'System.Nullable`1[System.DateTime]' (Parameter 'property')” exception
[英]How can i set system.nullable of datetime as an optional parameter in a subroutine?
我尝试了以下操作,但出现错误
需要常量表达式
Public Sub ExampleSub(ByVal Test as string,
Optional ByVal fromDate As System.Nullable(Of DateTime) = Date.Today)
'A Great sub!
End sub
这是C#
public void ExampleSub(string Test,
System.Nullable<DateTime> fromDate = System.DateTime.Today)
{
//A Great sub!
}
提前致谢
您不能,编译器会告诉您原因:)
在C#中:
public void ExampleSub(string Test)
{
//A Great overload!
ExampleSub(Test, System.DateTime.Now);
}
public void ExampleSub(string Test, System.Nullable<DateTime> fromDate)
{
//A Great sub!
}
现在,IFF您知道调用者不会合法传递null
,您可以这样做:
public void ExampleSub(string Test, System.Nullable<DateTime> fromDate = null)
{
fromDate = fromDate?? System.DateTime.Now;
//An Even Greater sub!
}
您不能对默认参数使用非常数表达式。 System.DateTime.Today
将取决于您运行程序的时间,因此它不是恒定的。
将常量表达式用作默认值,然后进行检查,然后在例程中将fromDate
设置为System.DateTime.Now
。 通常,像@sehes答案一样,将null
用作特殊值。 如果null
对您的代码有另一个特殊含义,则可以使用一个永远不会用作默认参数的值,例如System.DateTime.MinValue
:
public void ExampleSub(string Test,
System.Nullable<DateTime> fromDate = DateTime.MinValue)
{
fromDate = fromDate == DateTime.MinValue ? System.DateTime.Now : fromDate;
//A Great sub!
}
如果有人在VB.Net中这样做,这是我解决问题的一种方式,但在此线程上我没有找到确切的方法,如果它可以帮助某人:
/*I set below line as parameter in method*/
Optional ByVal SlotDate As DateTime = Nothing
If Not SlotDate = Nothing Then
/* code to execute when date passed */
Else
/* code to execute when there is no date passed */
End If
VB
Public Sub ExampleSub(Test As String, _
Optional fromDate As System.Nullable(Of DateTime) = Nothing)
'A Great sub!
If fromDate Is Nothing Then
'code here for no fromDate
'i.e. Now
fromDate = DateTime.Now
End If
End Sub
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.