如果DateTime是不可变的,为什么下列工作? [英] If DateTime is immutable, why does the following work?

查看:98
本文介绍了如果DateTime是不可变的,为什么下列工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以为我理解了Immutable的意思,但是我不明白为什么以下编译和工作:

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();

正如预期的那样,它运行,当我按回车,它会显示下一次...我以为这是不可能的,我需要创建一个新的对象。为什么允许/工作?或者,是我正在工作的这本书是错误的,而DateTime不是不可变的(但是我已经在几个来源上看过这个)?

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.

As pst 提到,但只读 const 可能更接近你的想法,你不能改变一个变量的值。

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.

旁注: DateTime 是一个结构,因此,值类型,我通过调用 dt 引用了一个'引用',但我认为 dt 仍然是一个变量'指向'不可变对象t,变量本身仍然是可变的。感谢 dan04 指出这一点。

Side note: DateTime is a Structure, and therefore, a value type, and I'm being misleading by calling dt a 'reference.' However, I think it still holds true that dt is still just a variable 'pointing' at an immutable object, and the variable itself is still mutable. Thanks to dan04 for pointing that out.

这篇关于如果DateTime是不可变的,为什么下列工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆