简体   繁体   English

DateTime.Now在一个语句中

[英]DateTime.Now within a statement

In the below thisIsAlwaysTrue should always be true. 在下面, thisIsAlwaysTrue应始终为true。

DateTime d = DateTime.Now;
bool thisIsAlwaysTrue = d == d;

But does DateTime.Now work in such a way that isThisAlwaysTrue is guaranteed to be true? 但DateTime.Now是否以这样的方式工作,即theThisAlwaysTrue保证是真的? Or can the clock change between references to the Now property? 或者可以在引用Now属性之间改变时钟?

bool isThisAlwaysTrue = DateTime.Now == DateTime.Now;

时钟肯定会在两次背靠背调用DateTime.Now之间发生变化。

The DateTime.Now property is volatile, meaning it definitely can change between uses. DateTime.Now属性是volatile,这意味着它肯定可以在使用之间更改。 But the variable you assign it to is not volatile. 但是你赋给它的变量不是易变的。

So this should always set result to true: 所以这应该始终将结果设置为true:

DateTime d = DateTime.Now;
bool result = d == d;

It assigns the value returned by DateTime.Now to the d variable, not the property itself. 它将DateTime.Now返回的值赋给d变量,而不是属性本身。 Thus d will always equal d in that code. 因此,d将始终等于该代码中的d。

But this will not always set result to true: 但这并不总是将结果设置为true:

bool result = DateTime.Now == DateTime.Now;

I would have to recommend you try this for yourself. 我不得不建议你自己尝试一下。 This code takes a fraction of second in the Release build: 此代码在Release版本中只需几分之一秒:

using System;

class Program {
  static void Main(string[] args) {
    while (DateTime.UtcNow == DateTime.UtcNow) ;
    Console.WriteLine("oops");
    Console.ReadLine();
  }
}

I trust it will repro well. 我相信它会很好。

DateTime is immutable, so it will never ever change once assigned. DateTime是不可变的,因此一旦分配就永远不会改变。 Your call to DateTime.Now doesn't "link" them - it just assigns whatever value DateTime.Now is at the time of calling to the variable d - it will not assign some sort of reference. 您对DateTime.Now的调用不会“链接”它们 - 它只是在调用变量d时分配DateTime.Now的任何 - 它不会分配某种引用。

So if you have a delay like this: 所以,如果你有这样的延迟:

DateTime d = DateTime.Now; // Let's assume it's 9:05:10
Thread.Sleep(100);
Console.WriteLine(d); // will still be 9:05:10, even though it's much later now

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

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