我得到E2010 Incompatible types: 'TDerivedFrame' and 'TBaseFrame'
以下代码:
type
TBaseFrame = class(TFrame)
end;
TDerivedFrame = class(TBaseFrame)
end;
TContainer<T: TBaseFrame> = class
private
FFrame: T;
public
property Frame: T read FFrame;
constructor Create;
end;
constructor TContainer<T>.Create;
begin
inherited;
FFrame := TBaseFrame(T).Create(nil);
end;
var
FTab: TContainer<TDerivedFrame>;
仅使用T.Create(nil)
原因E2568 Can't create new instance without CONSTRUCTOR constraint in type parameter declaration
。
据我所知,您只能使用无参数构造函数创建构造函数约束。
这样做的正确方法是什么?
PS:当我删除变量时代码编译,这让我认为这是编译器错误?!
编辑:我了解 E2010 错误,但即使使用T(TBaseFrame(T).Create(nil))
它也不起作用。这会编译,但会在运行时导致访问冲突:
type
TBaseFrame = class(TFrame)
public
constructor Create(AOwner: TComponent); override;
end;
TDerivedFrame = class(TBaseFrame)
public
constructor Create(AOwner: TComponent); override;
end;
TContainer<T: TBaseFrame> = class
private
FFrame: T;
public
property Frame: T read FFrame;
constructor Create;
end;
constructor TBaseFrame.Create(AOwner: TComponent);
begin
inherited;
end;
constructor TDerivedFrame.Create(AOwner: TComponent);
begin
inherited;
end;
constructor TContainer<T>.Create;
begin
inherited;
FFrame := T(TBaseFrame(T).Create(nil));
end;
var
FTab: TContainer<TDerivedFrame>;
begin
FTab := TContainer<TDerivedFrame>.Create;
end.