作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有一个返回引用类型的函数。现在,这个函数有两个可选参数,它们都是 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
注意命名参数以区分 start
和 end
值。
关于c# - 如何创建可选的 DateTime 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25208969/
我正在尝试用 Swift 编写这段 JavaScript 代码:k_combinations 到目前为止,我在 Swift 中有这个: import Foundation import Cocoa e
我是一名优秀的程序员,十分优秀!