更新时间:2023-11-12 17:48:40
(为了清楚起见,我在这里给出的解释特定于 Java 和 C#.不要假设它适用于其他语言,尽管有些可能.)
(Just to be clear, the explanation I'm giving here is specific to Java and C#. Don't assume it applies to other languages, although bits of it may.)
我喜欢用一个比喻来告诉别人我住在哪里.我可能会在一张纸上写下我的地址:
I like to use an analogy of telling someone where I live. I might write my address on a piece of paper:
这有帮助吗?
值类型和引用类型之间的区别是写在纸上的.例如,这里:
The difference between a value type and a reference type is what gets written on the piece of paper. For example, here:
int x = 12;
就像一张纸,上面直接写着数字12.鉴于:
is like having a piece of paper with the number 12 written on it directly. Whereas:
Dog myDog = new Dog();
不会将 Dog 对象本身的内容写在纸上 - 它会创建一个新的 Dog
,然后在该纸上写入对狗的引用.
doesn't write the Dog object contents itself on the piece of paper - it creates a new Dog
, and then writes a reference to the dog on that paper.
在非类比方面:
Button
变量,该值将始终是对 Button
类型的对象或某个子类的引用 - 或 null
参考.)Button
variable, the value will always be a reference to an object of type Button
or some subclass - or the null
reference.)