加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在Delphi中创建自身实例的类函数

发布时间:2020-12-15 04:15:49 所属栏目:大数据 来源:网络整理
导读:你有一个类函数可以创建一个类的实例: TMyClass = class(TSomeParent)public class function New(AValue : integer) : TMyClass; end;TDerivedClass = class(TMyClass)public function Beep;end; 然后按如下方式使用它 ... var myList : TListT; item : TDe
你有一个类函数可以创建一个类的实例:
TMyClass = class(TSomeParent)
public
  class function New(AValue : integer) : TMyClass; 
end;

TDerivedClass = class(TMyClass)
public
  function Beep;
end;

然后按如下方式使用它

...   
var
  myList : TList<T>;
  item : TDerivedClass;
begin
  myList.Add(TDerivedClass.New(1))
  myList.Add(TDerivedClass.New(3))
  myList.Add(TDerivedClass.New(5))

  for item in myList do
    item.Beep; //times the count in the class function
...

如果是这样,那个功能代码是什么样的?您是否使用TObject的NewInstance方法并且每次为每个派生类重新实现?使用构造函数是否更安全/更好?

目标是在命令模式中使用此方法并使用类类型和接收器加载命令列表,例如:

//FYI: document is an instance of TDocument
commandList.Execute(TOpenDocument(document)); 
commandList.Execute(TPasteFromClipboard(document)); 
//... lots of actions - some can undo
commandList.Execute(TPrintDocument(document)); 
commandList.Execute(TSaveDocument(document));

原因是某些命令将通过文本/脚本指定,需要在运行时解析.

解决方法

Can you have a class function that creates an instance of a class.
Is it saver/better to use the Constructor?

构造函数是一个创建类实例的类函数.
刚刚放:

constructor New(); virtual;

你很高兴.

虚拟; part将允许您为所有后代类调用相同的New()构造函数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读