在可选参数中设置日期时间的默认值
如何在可选参数中设置日期时间的默认值?
public SomeClassInit(Guid docId, DateTime addedOn = DateTime.Now???)
{
//Init codes here
}
How can I set default value for DateTime in optional parameter?
public SomeClassInit(Guid docId, DateTime addedOn = DateTime.Now???)
{
//Init codes here
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
有一个解决方法,利用可为 null 的类型以及
null
是编译时常量这一事实。 (不过,这有点像黑客,我建议避免它,除非你真的不能。)一般来说,我更喜欢其他答案中建议的标准重载方法:
There is a workaround for this, taking advantage of nullable types and the fact that
null
is a compile-time constant. (It's a bit of a hack though, and I'd suggest avoiding it unless you really can't.)In general, I'd prefer the standard overloading approach suggested in the other answers:
我猜您并不真正想要
addedOn = DateTime.Now
因为这意味着您永远不会得到任何结果,因为所有内容都会在“Now”之前添加。 :)默认的
DateTime
可以这样设置:更新
如果您使用 SQL Server,请不要忘记它不接受默认值(DateTime),即 1/1/0001。 SQL Server 的最小日期时间是 1/1/1753 (解释)。不过,SQL 的 DateTime2 接受 1/1/0001。
I guess that you did not really want
addedOn = DateTime.Now
because that would suggest you never get any result as everything would be added before 'Now'. :)A default
DateTime
can be set like this:Update
If you deal with SQL Server, do not forget that it doesn't accept default(DateTime) what is 1/1/0001. SQL Server's minimal DateTime is 1/1/1753 (explanation). SQL's DateTime2 accepts 1/1/0001, though.
我会稍微修改 LukeH 的解决方案:
它看起来更短且更具可读性。
I'd slightly modify LukeH's solution as:
which is shorter and more readable, it seems.
不要使用可选参数:
Don't use an optional parameter:
.NET 4.0 确实有可选参数。 (google 也是你的朋友,在这里。)
编辑(因为 Anthony Pegram 正确,评论)...
是的,这就是你要做的事情。但是
DateTime.
Now(静态属性,在该类上)直到运行时才知道嗯>。因此,您不能将其用作可选值。值。.NET 3.5 没有......所以你必须按照 JS Bangs 所说的那样......
或者甚至是 munificent 的答案中的空检查/空值参数。
干杯安东尼。
.NET 4.0 does have optional parameters. (google is also your friend, here.)
EDIT (because of Anthony Pegram correct, comment)...
And yes, that is how you would do it.But
DateTime.
Now (static property, on that class) is not know until run-time. As such, you can't use that as an optional value..NET 3.5 doesn't ... so then you would have to do what JS Bangs said...
or even the null checking/null value parameter from munificent's answer.
Cheers Anthony.
从这个意义上来说,C# 没有可选参数。如果您想让
addedOn
成为可选,您应该编写一个不需要该参数的重载,并将DateTime.Now
传递给两个参数的版本。C# doesn't have optional parameters in this sense. If you want to make
addedOn
optional, you should write an overload that doesn't require that parameter, and passesDateTime.Now
to the two-argument version.