如果日期时间是不可改变的,为什么下面的工作?日期、时间、工作

由网友(yi杯敬朝阳)分享简介:我想我明白了永恒的意思,但是我不明白为什么下面的编译和作品:I thought I understood what Immutable meant, however I don't understand why the following compiles and works:DateTime dt = DateT...

我想我明白了永恒的意思,但是我不明白为什么下面的编译和作品:

I thought I understood what Immutable meant, however I don't understand why the following compiles and works:

DateTime dt = DateTime.Now;

Console.WriteLine(dt);

复制并几次粘贴到下一部分

Copy and paste the next part a few times

dt = DateTime.Now;
Console.WriteLine(dt);
Console.ReadLine();

正如预期的那样,它运行,而当我preSS进入,它会显示下一次......我认为这是不可能的,我需要创建一个新的对象。这是为什么允许/工作?或者说,是这本书我从错误的工作和日期时间并不是一成不变的(不过我有几个来源阅读本)?

As expected, it runs, and when I press enter, it then displays the next time... I thought this was not possible and I would need to create a new object. Why is this allowed/working? Or, is the book I am working from wrong and DateTime is not immutable (However I have read this on several sources)?

推荐答案

的DateTime 对象本身是不可变的,但不参考DT 。 DT 允许更改的的DateTime 反对它指向。不变性指的是我们不能改变一个的DateTime 对象内部变量的事实。

The DateTime object itself is immutable, but not the reference dt. dt is allowed to change which DateTime object it points to. The immutability refers to the fact we can't change the variables inside a DateTime object.

例如,我们不能

dt.Day = 3;

DT 本身只是一个指向朝的DateTime 对象的引用变量。通过它的定义,它是允许的变化的。

dt itself is just a reference variable that points towards a DateTime object. By its definition, it's allowed to vary.

由于 PST 提到,虽然的只读和常量可能更接近于你在想什么,在这里你不能改变一个变量的值。

As pst mentioned, though, readonly and const are probably closer to what you're thinking, where you can't change the value of a variable.

附注:日期时间是一个的

阅读全文

相关推荐

最新文章