[英]How can i set system.nullable of datetime as an optional parameter in a subroutine?
I tried the following, but i get the error 我尝试了以下操作,但出现错误
constant expression is required
需要常量表达式
Public Sub ExampleSub(ByVal Test as string,
Optional ByVal fromDate As System.Nullable(Of DateTime) = Date.Today)
'A Great sub!
End sub
and here is the C# 这是C#
public void ExampleSub(string Test,
System.Nullable<DateTime> fromDate = System.DateTime.Today)
{
//A Great sub!
}
Thanks in advance 提前致谢
You can't, the compiler tells you why :) 您不能,编译器会告诉您原因:)
in C#: 在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!
}
Now, IFF you know that null
will not be legitimately by passed in by a caller, you could do: 现在,IFF您知道调用者不会合法传递
null
,您可以这样做:
public void ExampleSub(string Test, System.Nullable<DateTime> fromDate = null)
{
fromDate = fromDate?? System.DateTime.Now;
//An Even Greater sub!
}
You can't use a non-constant expression for the default parameter. 您不能对默认参数使用非常数表达式。
System.DateTime.Today
will depend on when you run the program so it is not constant. System.DateTime.Today
将取决于您运行程序的时间,因此它不是恒定的。
Use a constant expression for default and then check for that and set fromDate
to System.DateTime.Now
in the routine. 将常量表达式用作默认值,然后进行检查,然后在例程中将
fromDate
设置为System.DateTime.Now
。 Normally null
would be used as the special value as in @sehes answer. 通常,像@sehes答案一样,将
null
用作特殊值。 If null
has another special meaning to your code you could use a value which will never be used as the defaul parameter, eg System.DateTime.MinValue
: 如果
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!
}
If someone is doing this in VB.Net this is a way I solved my issue, I didn't find the exact thing on this thread, if it helps someone: 如果有人在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 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.