要从一个对象复制到另一个对象,我可以直接分配变量,还是必须分别分配变量的属性? [英] To copy from one object to another, can I assign the variables directly, or must I assign their properties individually?

查看:64
本文介绍了要从一个对象复制到另一个对象,我可以直接分配变量,还是必须分别分配变量的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想澄清一个疑问。在我当前的项目中,我发现有两个TClientDataSet组件。并将一个客户端数据集的属性和事件处理程序分配给另一客户端数据集,如下所示:

I would like to clarify one doubt. In my current project I find that there are two TClientDataSet components. And one client dataset's properties and event handlers are assigned to another client dataset as below:

  cds2.AfterApplyUpdates := cds1.AfterApplyUpdates;
  cds2.AfterCancel       := cds1.AfterCancel;
  cds2.AfterClose        := cds1.AfterClose;

  cds2.CommandText       := cds1.CommandText;
  cds2.AutoCalcFields    := cds1.AutoCalcFields;
  cds2.DisableStringTrim := cds1.DisableStringTrim;

上面的事件处理程序和属性分配是否必需?

Is the above assignment of event handlers and properties required?

如果我们仅按如下所示将一个客户数据集分配给另一个客户数据集,这还不够吗?

If we simply assign one client dataset to another as shown below, isn't it enough?

  cds2 := cds1;


推荐答案

Delphi类是引用类型。这意味着,当您定义类型为类的变量时,实际上拥有的是对该对象的引用或指针。这使得赋值运算符:= 的含义是引用赋值,而不是值赋值。

Delphi classes are reference types. That means that when you define a variable whose type is a class, what you actually have is a reference, or pointer, to the object. And that makes the meaning of the assignment operator := be reference assignment rather than value assignment.

假设您有以下声明:

var
  o1, o2: TObject;
....
o1 := TObject.Create;
o2 := o1;

至此,您已经创建了一个对象,并且都创建了 o1 o2 引用或指向同一对象。通过 o1 引用进行的任何更改也可以通过 o2 引用看到,因为只有一个对象或实例。

At this point, you have created one object, and both o1 and o2 refer to, or point to, the same object. Any changes you make through the o1 reference are also visible through the o2 reference since there is only one object, or instance.

因此,在您的情况下,您有 cds1 cds2 大概是指不同的实例。

So, in your scenario, you have cds1 and cds2 that, presumably, refer to different instances. And that means that

cds2.CommandText := cds1.CommandText;

cds1.CommandText 的值复制到 cds2.CommandText

完全不同于

cds2 := cds1;

这会复制引用,并导致您无法跟踪的单独对象cds2 指向。

which copies references, and results in you losing track of the separate object that cds2 refers to.

在此处查找有关引用类型和值类型的更多讨论:为什么我们应该使用类而不是记录,反之亦然?

Find more discussion of reference types and value types here: Why should we use classes rather than records, or vice versa?.

,您呈现的两个选项会做非常不同的事情。您当前使用的复制属性值的代码大概可以正常工作。在这种情况下,建议的复制引用更改肯定不会满足您的要求。

In summary, the two options that you present do very different things. The code that you currently use, which copies property values, presumably works. In which case, your suggested change to copy references will certainly not do what you want.

这篇关于要从一个对象复制到另一个对象,我可以直接分配变量,还是必须分别分配变量的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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