C# 新日期时间()与默认(日期时间)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13957701/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
new DateTime() vs default(DateTime)
提问by RJP
Is there a reason to choose one of these over the other?
有没有理由选择其中一个而不是另一个?
DateTime myDate = new DateTime();
or
或者
DateTime myDate = default(DateTime);
Both of them are equal 1/1/0001 12:00:00 AM
.
他们俩是平等的1/1/0001 12:00:00 AM
。
采纳答案by Servy
No, they are identical.
不,它们是相同的。
default()
, for any value type (DateTime
is a value type) will always call the parameterless constructor.
default()
, 对于任何值类型(DateTime
是值类型)将始终调用无参数构造函数。
回答by Ben C
The answer is no. Keep in mind that in both cases, mdDate.Kind = DateTimeKind.Unspecified
.
答案是不。请记住,在这两种情况下,mdDate.Kind = DateTimeKind.Unspecified
.
Therefore it may be better to do the following:
因此,最好执行以下操作:
DateTime myDate = new DateTime(1, 1, 1, 0, 0, 0, DateTimeKind.Utc);
The myDate.Kind
property is readonly, so it cannot be changed after the constructor is called.
该myDate.Kind
属性是只读的,因此在调用构造函数后无法更改。
回答by Tomer
If you want to use default value for a DateTime parameter in a method, you can only use default(DateTime).
如果要在方法中为 DateTime 参数使用默认值,则只能使用 default(DateTime)。
The following line will not compile:
以下行不会编译:
private void MyMethod(DateTime syncedTime = DateTime.MinValue)
This line will compile:
这一行将编译:
private void MyMethod(DateTime syncedTime = default(DateTime))
回答by G.Busato
The simpliest way to understand it is that DateTime is a struct. When you initialize a struct it's initialize to it's minimum value : DateTime.Min
理解它的最简单方法是 DateTime 是一个结构体。初始化结构时,它会初始化为最小值:DateTime.Min
Therefore there is no difference between default(DateTime)
and new DateTime()
and DateTime.Min
因此default(DateTime)
和new DateTime()
和没有区别DateTime.Min