简体   繁体   English

如何在C#中克隆DateTime对象?

[英]How can I clone a DateTime object in C#?

如何在C#中克隆DateTime对象?

DateTime is a value type ( struct ) DateTime是一个值类型struct

This means that the following creates a copy: 这意味着以下内容创建了一个副本:

DateTime toBeClonedDateTime = DateTime.Now;
DateTime cloned = toBeClonedDateTime;

You can also safely do things like: 您还可以安全地执行以下操作:

var dateReference = new DateTime(2018, 7, 29);
for (var h = 0; h < 24; h++) {
  for (var m = 0; m < 60; m++) {
    var myDateTime = dateReference.AddHours(h).AddMinutes(m);
    Console.WriteLine("Now at " + myDateTime.ToShortDateString() + " " + myDateTime.ToShortTimeString());
  }
}

Note how in the last example myDateTime gets declared anew in each cycle; 注意在最后一个例子中myDateTime如何在每个循环中重新声明; if dateReference had been affected by AddHours() or AddMinutes() , myDateTime would've wandered off really fast – but it doesn't, because dateReference stays put: 如果dateReferenceAddHours()AddMinutes()myDateTime会非常快地离开 - 但它没有,因为dateReference保持put:

Now at 2018-07-29 0:00
Now at 2018-07-29 0:01
Now at 2018-07-29 0:02
Now at 2018-07-29 0:03
Now at 2018-07-29 0:04
Now at 2018-07-29 0:05
Now at 2018-07-29 0:06
Now at 2018-07-29 0:07
Now at 2018-07-29 0:08
Now at 2018-07-29 0:09
...
Now at 2018-07-29 23:55
Now at 2018-07-29 23:56
Now at 2018-07-29 23:57
Now at 2018-07-29 23:58
Now at 2018-07-29 23:59
var original = new DateTime(2010, 11, 24);
var clone = original;

DateTime is a value type, so when you assign it you also clone it. DateTime是一个值类型,因此在分配时也可以克隆它。 That said, there's no point in cloning it because it's immutable; 也就是说,克隆它是没有意义的,因为它是不可改变的; typically you'd only clone something if you had the intention of changing one of the copies. 通常,如果您打算更改其中一个副本,则只能克隆一些内容。

DateTime is a value type so everytime you assign it to a new variable you are cloning. DateTime是一个值类型,因此每次将它分配给您正在克隆的新变量时。

DateTime foo = DateTime.Now;
DateTime clone = foo;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM