【问题标题】:How can I tell if one TClass is derived from another?如何判断一个 TClass 是否派生自另一个?
【发布时间】:2011-11-22 14:39:35
【问题描述】:

我正在尝试做这样的事情:

function CreateIfForm ( const nClass : TClass ) : TForm;
begin
  if not ( nClass is TFormClass ) then
    raise Exception.Create( 'Not a form class' );
  Result := ( nClass as TFormClass ).Create( Application );
end;

这会产生错误“运算符不适用于此操作数类型”。 我正在使用 Delphi 7。

【问题讨论】:

  • 别忘了接受答案 ;-)

标签: delphi class delphi-7


【解决方案1】:

首先您应该检查是否可以将函数更改为仅接受表单类:

function CreateIfForm(const nClass: TFormClass): TForm;

并绕过类型检查和强制转换的需要。

如果这不可能,您可以使用InheritsFrom

function CreateIfForm(const nClass: TClass): TForm;
begin
  if not nClass.InheritsFrom(TForm) then
    raise Exception.Create('Not a form class');
  Result := TFormClass(nClass).Create(Application);
end;

【讨论】:

  • 继承自!是的,这正是我正在寻找的。谢谢
  • @Ulrich -- 您的第二个答案确实是正确的:该函数甚至不应该接受不是表单的类。
  • @Nick,当然是你的权利。我改写了我的答案以更好地反映这一点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-07
  • 1970-01-01
  • 1970-01-01
  • 2011-03-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多