如果日期时间是不可改变的,为什么下面的工作? [英] If DateTime is immutable, why does the following work?

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

问题描述

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

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.

附注:日期时间是一个的Structure 时,并且因此,一<​​A HREF =htt​​p://msdn.microsoft.com/en-us/library/t63sy5hs% 28V = VS.80%29.aspx>值类型,而我是误导性的,通过调用 DT 一个参考。但是,我认为它仍然适用的 DT 目前还只是一个变量指向的不可变对象,和变量本身仍然是可变的。由于 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.

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

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