delphi对象分配vs:= [英] delphi object assign vs :=

查看:69
本文介绍了delphi对象分配vs:=的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以解释一下两者之间的区别吗?

Could someone explain the difference between:

(1。)

newObj := TMyObject.Create;
newObj.Assign(oldObj);

(2。)

newObj := oldObj;

在2中。 newObj oldObj 是指同一个对象吗?

in 2. does newObj and oldObj refer to the same single object?

对不起,如果以前已经讨论过,但是很难搜索:=

Sorry if this has been covered before but is is difficult to search :=

推荐答案

newObj := TMyObject.Create; 
newObj.Assign(oldObj);

假设分配的实施正确,


  • 创建 TMyObject 的新实例(通过 Create

  • 将对该实例的引用存储在变量 newObj 中(通过:= 运算符)

  • 执行 oldObj 的深层副本,使 newObj oldObj 的功能完全相同的副本(通过 Assign )。

  • creates a new instance of TMyObject (via Create)
  • stores a reference to that instance in the variable newObj (via the := operator)
  • Performs a deep copy of oldObj, making newObj a functionally exact copy of oldObj (via Assign).

这里的最终结果是,您有两个完全独立的 TMyObject 实例。点,彼此的精确副本。

The end result here is that you have two completely separate instances of TMyObject which are, at this point, exact copies of each other.

newObj := oldObj;

以上只是复制了对 oldObj 的引用并将其存储在变量 newObj 中。在这种情况下,您仍然只有一个 TMyObject 实例,以及两个变量 newObj oldObj 指向同一实例。如果使用任何一个变量修改该对象的状态,由于它们都指向同一基础对象,因此两者都将反映这些更改。

The above simply copies a reference to oldObj and stores it in the variable newObj. In this case you still only have one instance of TMyObject and both variables newObj and oldObj point to the same instance. If you modify the state of that object using either variable, both will reflect those changes since they both point to the same underlying object.

与上面的示例相反,您有两个单独的对象,它们的状态可能会发生变化,因为两个对象都是独立修改的。

This is in contrast to the example above where you have two separate object whose state can diverge as both objects are modified independently.

概念上,对象(类)的变量通常称为 引用类型。这种类型的变量本质上只是指针(如果更熟悉)。具有引用类型的赋值(:= )仅将引用复制到对象,而不是对象本身。

Conceptually, variables of objects (classes) are generally referred to as "reference types". Variables of this type are essentially just pointers (if this is more familiar). Assignment (:=) with reference types only copies the reference to the object, not the object itself.

唯一的实质性例外是 string 类型,这些类型具有引用类型的许多属性,但是由编译器还可以在许多方面表现为值类型(修改字符串会产生新的修改后的副本,而不是修改可能在其他地方引用的原始字符串)。

The only material exception to this are string types, which have many properties of reference types, but are managed by the compiler to also behave in many ways as value types (modifying a string produces a new modified copy rather than modifying the original string which may be referenced elsewhere).

另请参见:要从一个对象复制到另一个对象,我可以分配变量直接还是我必须分别分配它们的属性?

这篇关于delphi对象分配vs:=的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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