如何创建可选的DateTime参数?
我有这个函数返回一个引用类型。 现在,这个函数有两个可选参数,它们都是DateTime
类的实例。 function是这样的:
public DateTime GetDate(DateTime start = DateTime.MinValue, DateTime end = DateTime.MinValue) { // Method body... }
VS的错误是:
‘start’的默认参数值必须是编译时常量
当然,错误适用于第二个参数,我完全理解发生了什么。
我真正想要的是知道是否有办法解决这个问题,即在方法中有可选参数。 现在,我所做的就是创造一个过载; 我的意思是,我创建了一个无参数函数GetDate()
和它的双参数重载。
这不是一个真正的问题,但我只是想知道是否有办法做到这一点。
一种解决方法是像这样分配它们:
public DateTime GetDate(DateTime? start = null, DateTime? end = null){ start = start ?? DateTime.MinValue; end = end ?? DateTime.MinValue; Console.WriteLine ("start: " + start); Console.WriteLine ("end: " + end); return DateTime.UtcNow; }
哪个可以这样使用:
void Main() { new Test().GetDate(); new Test().GetDate(start: DateTime.UtcNow); new Test().GetDate(end: DateTime.UtcNow); new Test().GetDate(DateTime.UtcNow, DateTime.UtcNow); }
并按预期工作:
start: 1/01/0001 0:00:00 end: 1/01/0001 0:00:00 start: 8/08/2014 17:30:29 end: 1/01/0001 0:00:00 start: 1/01/0001 0:00:00 end: 8/08/2014 17:30:29 start: 8/08/2014 17:30:29 end: 8/08/2014 17:30:29
请注意命名参数以区分start
值和end
值。
顺便说一句,你不必像所有其他答案那样使用可空的日期时间。 您也可以使用DateTime
执行此操作:
public DateTime GetDate( DateTime start = default(DateTime), DateTime end = default(DateTime)) { start = start == default(DateTime) ? DateTime.MinValue : start; end = end == default(DateTime) ? DateTime.MinValue : end; }
这不太可能,但如果您实际将默认日期时间值传递给函数,它将无法按预期工作。
您可以将DateTime
设置为可为空,然后如果未提供参数则转换为DateTime.Min
:
public DateTime GetDate(DateTime? start = null, DateTime? end = null) { var actualStart = start ?? DateTime.Min; var actualEnd = end ?? DateTime.Min; }
唯一的方法是这样做(更多的代码,但它给你可选的args):
上述就是C#学习教程:如何创建可选的DateTime参数?分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
public DateTime GetDate(DateTime? start = null, DateTime? end = null) { // Method body... if(start == null) { start = DateTime.MinValue; } //same for end }
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/1017800.html