且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

变量、对象和引用之间有什么区别?

更新时间: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 参考.)
  • 对象是一种独立的实体.重要的是,变量或任何表达式的值永远是一个对象,只是一个引用.一个对象有效地包括:
    • 字段(状态)
    • 类型引用(在对象的生命周期内永远不会改变)
    • 监视器(用于同步)
    • 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 type Button or some subclass - or the null 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)