如何在Spring4D中使用多接口类

aQu*_*Quu 2 delphi interface spring4d

我刚刚学习Spring4D,我有一个问题.如果类只实现一个接口,则全部清除:

    IWeapon = interface
        ['{E679EDA6-5D43-44AD-8F96-3B5BD43A147B}']
        procedure Attack;
    end;

    TSword = class(TInterfacedObject, IWeapon)
    public
        procedure Attack;
    end;

    GlobalContainer.RegisterType<TSword>.Implements<IWeapon>('sword');
    sword := ServiceLocator.GetService<IWeapon>('sword');
Run Code Online (Sandbox Code Playgroud)

我现在很高兴,我有剑,我不需要释放它.

但是如果类实现了两个或更多接口:

    IWeapon = interface
        ['{E679EDA6-5D43-44AD-8F96-3B5BD43A147B}']
        procedure Attack;
    end;

    IShield = interface
        ['{B2B2F443-85FE-489C-BAF4-538BB5B377B3}']
        function Block: Integer;
    end;

    TSpikedShield = class(TInterfacedObject, IWeapon, IShield)
    public
        function Block: Integer;
        procedure Attack;
    end;

    GlobalContainer.RegisterType<TSpikedShield>.Implements<IWeapon>.Implements<IShield>;
Run Code Online (Sandbox Code Playgroud)

我可以向ServiceLocator询问TSpikedShield的实例,但我需要选择一个IWeapon或IShield.但我想以两种方式使用它(或者我不应该想要?),如:

spikedShield.Attack;
spikedShield.Block;
Run Code Online (Sandbox Code Playgroud)

所以如果我很好看,我必须直接创建TSpikedShiled的实例(我的意思是没有接口).

function MakeSpikedShield: TSpickedShield;
begin
    result := TSpickedShield.Create;
end;
Run Code Online (Sandbox Code Playgroud)

有没有办法使用这个类,但有自动免费?

(如果接口可以实现多次干扰但在delphi中不允许,则不会有问题)

编辑:也许是这样的想法?

ISpikedSield = interface
    function AsWeapon: IWeapon;
    function AsShield: IShield;
end;
TSpikedShield = class(TInterfacedObject, ISpikedShield)
Run Code Online (Sandbox Code Playgroud)

Ste*_*nke 6

如果接口可以实现多接口,那么将不存在问题,但在Delphi中不允许这样做

这就是问题的确切原因.

我只想做一个ISpikedShield有方法接口IWeaponIShield并确保每一个实现类ISpikedShield也明确实现IWeaponIShield(这是编译器基本上在C#中为你所做的例子,其中一个接口可以从多个其他接口继承).

然后,您无法分配ISpikedShield给a IWeapon,IShield但使用as运算符将起作用,因为后面的类实现它们.

但是我不确定你的体系结构中是否存在误解,因为如果你进一步思考,就不会有一个具有ISpikedShield依赖性的类,而是一个IWeapon和/或IShield.然后,一些游戏代码将检查您是否IShield支持ICanAttack除了您可以执行的操作之外还要进行额外的操作IWeapon.