[英]Converting Object Instance to Reference of another Instance?
In my framework I have a DataSource1 instance that was dropped in design time on a Form. 在我的框架中,我有一个DataSource1实例,该实例在设计时已被丢弃在Form上。
At some point at run time I need to "convert" it to a reference to another DataSource2 (on a Data Module). 在运行时的某个时刻,我需要将其“转换”为对另一个DataSource2的引用(在数据模块上)。
Is simply setting: 只是设置:
DataSource1 := DataSource2;
Enough to make DataSource1 a reference of DataSource2? 是否足以使DataSource1成为DataSource2的引用? it appears that DataSource1 is not being destroyed at this point - It is destroyed when the Owner of DataSource2 is destroyed, And that there are in fact two instances of TDataSource.
似乎此时DataSource1尚未被销毁-当销毁DataSource2的所有者时销毁了它,并且实际上有两个TDataSource实例。
Or do I need to explicitly free DataSource1 first? 还是我需要首先显式释放DataSource1?
DataSource1.Free;
DataSource1 := DataSource2;
What is the correct way? 正确的方法是什么? (Besides declaring DataSource1 as a reference in the first place)
(除了首先声明将DataSource1作为参考)
When you declare a variable to be of a type that inherits from TObject, you are actually declaring a pointer. 当您声明变量具有从TObject继承的类型时,实际上是在声明一个指针。
When you call a constructor, you are creating an instance. 调用构造函数时,您正在创建一个实例。 The constructor returns a pointer to that instance.
构造函数返回一个指向该实例的指针。 You typically assign that pointer to a variable like this:
通常,您将指针分配给这样的变量:
Obj1 := TMyClass.Create;
You can make a second variable point to, or refer to, the instance with simple assignment: 您可以通过简单的分配使第二个变量指向或引用实例:
Obj2 := Obj1;
The object is destroyed by calling Free: 通过调用Free销毁对象:
Obj1.Free;
At this point Obj2 refers to an object that no longer exists. 此时,Obj2引用的对象不再存在。 We say that Obj2 is a stale reference.
我们说Obj2是陈旧的参考。
In your case you need to free the first object: 您需要释放第一个对象:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.