如何创建可选的DateTime参数?

afa*_*lek 11 c# reference-type optional-parameters

我有这个函数返回一个引用类型.现在,这个函数有两个可选参数,这两个参数都是DateTime类的实例.功能是这样的:

public DateTime GetDate(DateTime start = DateTime.MinValue, DateTime end = DateTime.MinValue)
{
    // Method body...
}
Run Code Online (Sandbox Code Playgroud)

VS的错误是:

'start'的默认参数值必须是编译时常量

当然,错误适用于第二个参数,我完全理解发生了什么.

我真正想要的是知道是否有办法解决这个问题,即在方法中有可选参数.现在,我所做的是创造一个过载; 我的意思是,我创建了一个无参数函数GetDate()和一个双参数重载.

这不是一个真正的问题,但我只是想知道是否有办法做到这一点.

Jer*_*vel 18

一种解决方法是像这样分配它们:

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;
}
Run Code Online (Sandbox Code Playgroud)

哪个可以这样使用:

void Main()
{
    new Test().GetDate();
    new Test().GetDate(start: DateTime.UtcNow);
    new Test().GetDate(end: DateTime.UtcNow);
    new Test().GetDate(DateTime.UtcNow, DateTime.UtcNow);
}
Run Code Online (Sandbox Code Playgroud)

并按预期工作:

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
Run Code Online (Sandbox Code Playgroud)

请注意命名参数以区分startend值.


Sel*_*enç 7

顺便说一下,你不必像所有其他答案那样使用可空的日期时间.你也可以这样做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;
}
Run Code Online (Sandbox Code Playgroud)

这不太可能,但如果您实际将默认日期时间值传递给函数,它将无法按预期工作.

  • default(DateTime) = new DateTime() = DateTime.MinValue (2认同)

Mar*_* N. 5

唯一的方法是这样做(更多的代码,但它为您提供了可选的参数):

public DateTime GetDate(DateTime? start = null, DateTime? end = null)
{
    // Method body...
    if(start == null)
    {
      start = DateTime.MinValue;
    }

    //same for end
}
Run Code Online (Sandbox Code Playgroud)


Nei*_*ith 5

您可以将 设为DateTime可为空,然后DateTime.Min在不提供参数的情况下转换为:

public DateTime GetDate(DateTime? start = null, DateTime? end = null) {
    var actualStart = start ?? DateTime.Min;
    var actualEnd = end ?? DateTime.Min;
}
Run Code Online (Sandbox Code Playgroud)