可能重複:嘗試投放使用
as
操作者一般類型時
「As」 operator for constrained generic types問題的泛型和鑄態
以下還原的樣品的代碼生成編譯錯誤。奇怪的是,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'cast無法用'不兼容類型'錯誤進行編譯。現在,問題是什麼? :-)順便說一下,這個演員似乎是多餘的。你可以安全地使用'T(FCtrl)',因爲'T'被限制爲'TControl'(或後代)。 – 2011-06-08 16:01:12
@TOndrej:問題是:爲什麼它會失敗?這是一個編譯器錯誤? – jpfollenius 2011-06-08 16:06:42
是的,我個人認爲它是一個編譯器錯誤。演員應該成功似乎是合乎邏輯的。另外,編譯器具有驗證這種演員需要的知識。 – 2011-06-08 16:09:51