如何创建可选的DateTime参数? [英] How can I create an optional DateTime parameter?

查看:64
本文介绍了如何创建可选的DateTime参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this function that returns a reference type. Now, this function has two optional parameters both of which are instances of the DateTime class. The function is something like this:

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

VS的错误是:

开始"的默认参数值必须为编译时常量

Default parameter value for 'start' must be a compile-time constant

当然,该错误适用于第二个参数,我完全理解正在发生的事情.

Of course, the error applies to the second parameter and I perfectly understand what is happening.

我真正想知道的是是否有办法解决该问题,即方法中具有可选参数.现在,我要做的是创建一个重载.我的意思是,我创建了一个无参数函数GetDate()并对其进行了两参数重载.

What I really want is to know if there is a way to go about this, that is, having optional parameters in the method. Right now, what I have done is to create an overload; I mean, I have created a parameterless function GetDate() and a two-parameter overload of it.

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

This is not really a problem but I just want to know if there is a way to do it.

推荐答案

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

One workaround is to assign them like this:

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值.

Note the named parameter to distinguish between the start and end value.

这篇关于如何创建可选的DateTime参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆