如何将祖先转换为后代?

时间:2018-12-01 13:25:14

标签: delphi interface casting multiple-inheritance

在下面的代码中:

type
    IFoo = interface
    end;

    IFoo<T> = interface(IFoo)
        procedure DoStuff(a: T);
    end;

    TFoo = class(TInterfacedObject, IFoo<Integer>, IFoo<string>, IFoo)
        procedure DoStuffInt(a: Integer);
        procedure DoStuffStr(a: string);
        procedure IFoo<Integer>.DoStuff = DoStuffInt;
        procedure IFoo<string>.DoStuff = DoStuffStr;
    end;

procedure TFoo.DoStuffInt(a: Integer);
begin
    Showmessage(a.ToString);
end;

procedure TFoo.DoStuffStr(a: string);
begin
    ShowMessage(a);
end;

var
    iint: IFoo<Integer>;
    istr: IFoo<string>;
    i: IFoo;
begin
    i := TFoo.Create;
    IFoo<integer>(i).DoStuff(123);  // error
    IFoo<string>(i).DoStuff('abc'); // error
end.

我想调用DoStuff方法,但不适用于我做的方法。如何正确投放?

详细信息: 我将要拥有将产生IFoo实例的工厂,然后将它们强制转换为具体的IFoo。

编辑: 对于一个界面,它的工作正常:

type
    IFoo = interface
    end;

    IFoo<T> = interface(IFoo)
        procedure DoStuff(a: T);
    end;

    TFoo = class(TInterfacedObject, IFoo<integer>, IFoo)
        procedure DoStuff(a: Integer);
    end;

procedure TFoo.DoStuff(a: Integer);
begin
    Showmessage(a.ToString);
end;

var
    i: IFoo;
begin
    i := TFoo.Create;
    IFoo<Integer>(i).DoStuff(123);
    // curiosity
    IFoo<string>(i).DoStuff('abc'); // it call DoStuff(a: Integer)

0 个答案:

没有答案