开发者

Problem with Generics and As Cast [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

“As” operator for constrained generic types

The following reduced sample code produces a compiler error when trying to cast to the generic type using the as operator. Strangely enough the combination of the is operator and a hard cast does work as expected.

program Project8;

{$APPTYPE CONSOLE}

uses
  SysUtils, Controls, StdCtrls;

type
  TControlWrapperBase = class
  protected
    FCtrl : TControl;
  public
    construct开发者_StackOverflow社区or 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.

How can this compiler error be overcome?


This is a known issue: "As" operator for constrained generic types

However, I don't understand why you can't write it like this:

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


You have already asked nearly the same question more than 2 years ago. I don't know what changed in Delphi generics since then, but probably Barry Kelly's answer is still valid - the compiler can't typecast generics because

Unfortunately, the compiler is not smart enough to figure out that a class-type constraint means that T is guaranteed to be the same size as a pointer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜