变量、对象和引用之间有什么区别? [英] What is the difference between a variable, object, and reference?
问题描述
变量、对象和引用之间究竟有什么区别?
Exactly what are the differences between variables, objects, and references?
例如:它们都指向某种类型,并且它们都必须持有值(当然除非你有临时的可为空的类型),但它们的功能和实现究竟有何不同?
For example: they all point to some type, and they must all hold values (unless of course you have the temporary null-able type), but precisely how are their functions and implementations different from each other?
示例:
Dog myDog = new Dog(); //variable myDog that holds a reference to object Dog
int x = 12; //variable x that hold a value of 12
它们有相同的概念,但它们有何不同?
They have the same concepts, but how are they different?
推荐答案
(为了清楚起见,我在这里给出的解释特定于 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
参考.) - 对象是一种独立的实体.重要的是,变量或任何表达式的值永远是一个对象,只是一个引用.一个对象有效地包括:
- 字段(状态)
- 类型引用(在对象的生命周期内永远不会改变)
- 监视器(用于同步)
- A variable represents a storage location in memory. It has a name by which you can refer to it at compile time, and at execution time it has a value, which will always be compatible with its compile-time type. (For example, if you've got a
Button
variable, the value will always be a reference to an object of typeButton
or some subclass - or thenull
reference.) - An object is a sort of separate entity. Importantly, the value of a variable or any expression is never an object, only a reference. An object effectively consists of:
- Fields (the state)
- A type reference (can never change through the lifetime of the object)
- A monitor (for synchronization)
这篇关于变量、对象和引用之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!