gpt4 book ai didi

c# - 如何创建可选的 DateTime 参数?

转载 作者:可可西里 更新时间:2023-11-01 08:54:02 24 4
gpt4 key购买 nike

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

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

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

我真正想要的是知道是否有办法解决这个问题,即在方法中包含可选参数。现在,我所做的是创建一个过载;我的意思是,我创建了一个无参数函数 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

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

关于c# - 如何创建可选的 DateTime 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25208969/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com