【问题标题】:How can I create an optional DateTime parameter?如何创建可选的 DateTime 参数?
【发布时间】:2014-08-08 17:26:50
【问题描述】:

我有这个返回引用类型的函数。现在,这个函数有两个可选参数,它们都是DateTime 类的实例。函数是这样的:

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

VS 的错误是:

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

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

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

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

【问题讨论】:

  • DateTime 是值类型而不是引用类型。
  • 我知道,这是我提问的目的。
  • 您的问题似乎是如何将两个 DateTime 参数指定为可选。这个问题根本不涉及引用类型。
  • 我认为标题足够明确。
  • 是的,但这里仍然没有引用类型。没有。

标签: c# optional-parameters reference-type


【解决方案1】:

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

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

注意命名参数以区分startend 值。

【讨论】:

  • 我实际上想过使用nullables,但我想知道如何将它传递给函数。当您的回答通过时,我正要对此发表评论。
  • 一个Nullable<T> 总是可以得到T 分配给它,你不必明确地进行转换。
  • 谢谢@jeroen-vannevel。
【解决方案2】:

顺便说一句,您不必像所有其他答案所说的那样使用可为空的日期时间。你也可以用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;
}

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

【讨论】:

  • 嗯...那么default(DateTime)的值是什么我不应该通过的?
  • 等于new DateTime()
  • default(DateTime) = new DateTime() = DateTime.MinValue
【解决方案3】:

您可以将DateTime 设置为可为空,如果没有提供参数,则转换为DateTime.Min

public DateTime GetDate(DateTime? start = null, DateTime? end = null) {
    var actualStart = start ?? DateTime.Min;
    var actualEnd = end ?? DateTime.Min;
}

【讨论】:

    【解决方案4】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-07-16
      • 2010-09-07
      • 2012-03-21
      • 2017-12-10
      • 2013-11-09
      • 1970-01-01
      • 2016-06-13
      • 2019-11-07
      相关资源
      最近更新 更多