gpt4 book ai didi

delphi - 泛型和 As Cast 的问题

转载 作者:行者123 更新时间:2023-12-02 04:06:57 25 4
gpt4 key购买 nike

Possible Duplicate:
“As” operator for constrained generic types

当尝试使用 as 转换为泛型类型时,以下简化示例代码会产生编译器错误。运算符(operator)。奇怪的是 is 的组合运算符和硬转换确实按预期工作。

program Project8;

{$APPTYPE CONSOLE}

uses
SysUtils, Controls, StdCtrls;

type
TControlWrapperBase = class
protected
FCtrl : TControl;
public
constructor Create (Ctrl : TControl);
end;

TControlWrapper <T : TControl> = class (TControlWrapperBase)
public
function GetControl : T;
end;


constructor TControlWrapperBase.Create(Ctrl : TControl);
begin
FCtrl := Ctrl;
end;


function TControlWrapper <T>.GetControl : T;
begin
Result := FCtrl as T; // does not compile: E2010 Incompatible Types: TEdit and TControl

if FCtrl is T then // this does work
Result := T (FCtrl);
end;

var
Wrapper : TControlWrapper <TEdit>;
MyCtl : TEdit;

begin
try
MyCtl := TEdit.Create(nil);
TControlWrapper <TEdit>.Create (MyCtl).GetControl;
except
on E: Exception do
Writeln(E.ClassName, ': ', E.Message);
end;

end.

如何克服这个编译器错误?

最佳答案

这是一个已知问题:"As" operator for constrained generic types

但是,我不明白为什么你不能这样写:

type
TControlWrapper<T: TControl> = class
private
FCtrl: T;
public
property Ctrl: T read FCtrl;
end;

关于delphi - 泛型和 As Cast 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6281307/

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