gpt4 book ai didi

c# - 使用 AddTicks 不会对 DateTime 造成影响

转载 作者:太空狗 更新时间:2023-10-29 22:04:46 26 4
gpt4 key购买 nike

我有以下 AddTicks 方法的代码。 datetime 对象的 Ticks 属性在 AddTick 方法前后返回相同的值。为什么会这样?

There are 10,000 ticks in a millisecond.

Ticks: The value of this property represents the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001, which represents DateTime.MinValue.

AddTicks : Adds the specified number of ticks to the value of this instance.

注意:我使用的是.Net 4.0框架

代码

    static void Main()
{


DateTime dt2 = new DateTime(2010, 5, 7, 10, 11, 12, 222);

long x = dt2.Ticks;
dt2.AddTicks(9999);

long y = dt2.Ticks;

bool isSame = false;
if (x == y)
{
isSame = true;
}


Console.WriteLine(isSame);
System.Console.ReadKey();
}

最佳答案

AddTicks(以及其他 Add* 方法)不会更改 DateTime,但会返回一个新对象。

所以你应该使用

dt2 = dt2.AddTicks(...)

DateTime 是一个值类型并且是不可变的。

关于c# - 使用 AddTicks 不会对 DateTime 造成影响,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14253824/

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