gpt4 book ai didi

delphi - 无法编译受约束的泛型方法

转载 作者:行者123 更新时间:2023-12-03 15:51:30 26 4
gpt4 key购买 nike

长话短说:以下代码无法在 Delphi 10.1 Berlin(更新 2)中编译。

interface

uses
System.Classes, System.SysUtils;

type
TTest = class(TObject)
public
function BuildComponent<T: TComponent>(const AComponentString: String): T;
end;

TSomeComponent = class(TComponent)
public
constructor Create(AOwner: TComponent; const AString: String); reintroduce;
end;

implementation

{ TTest }

function TTest.BuildComponent<T>(const AComponentString: String): T;
begin
if T = TSomeComponent then
Result := TSomeComponent.Create(nil, AComponentString)
else
Result := T.Create(nil);
end;

{ TSomeComponent }

constructor TSomeComponent.Create(AOwner: TComponent; const AString: String);
begin
inherited Create(AOwner);
end;

编译器发出几条错误消息:

  1. E2015: Operator not applicable to this operand type

    在线如果 T = TSomeComponent 那么

  2. E2010 Incompatible types - 'T' and 'TSomeComponent'

    在线Result := TSomeComponent.Create(nil, AComponentString)

为了规避这些问题,我可以强制转换 TClass(T) (对于 #1),如 LU RD's answer here 中所述。 (尽管据说,这个错误已经在XE6中得到修复)和T(TSomeComponent.Create(nil, AComponentString))(对于#2)。尽管如此,我对使用显式类型转换感到不舒服。

还有更好的办法吗?难道编译器不应该识别出 TTComponent 类型吗,因为我显式地约束了它?

<小时/>

首先,我尝试像声明接口(interface)一样声明通用函数的实现:

function TTest.BuildComponent<T: TComponent>(const AComponentString: String): T;

但这最终导致了错误

E2029: ',', ';' or '>' expected but ':' found

最佳答案

这不能在我遇到的任何版本的 Delphi 中编译。您需要进行一些转换来说服编译器编译此内容:

function TTest.BuildComponent<T>(const AComponentString: String): T;
begin
if TClass(T) = TSomeComponent then
Result := T(TSomeComponent.Create(nil, AComponentString))
else
Result := T(TComponentClass(T).Create(nil));
end;

也就是说,我想我可能更喜欢:

if TClass(T).InheritsFrom(TSomeComponent) then

代替平等测试。

即便如此,尝试将具有不同参数的新构造函数拼接到基于虚拟构造函数的类对我来说似乎是一场灾难。

关于delphi - 无法编译受约束的泛型方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44308452/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com