【问题标题】:Casting a delphi interface to its implementation class without modifying the interface [duplicate]在不修改接口的情况下将delphi接口转换为其实现类[重复]
【发布时间】:2011-09-18 20:38:57
【问题描述】:

可能重复:
How to cast a Interface to a Object in Delphi

使用 Delphi 5;我有一个由于遗留原因无法更改的界面。我在各处传递(指向)该接口。实现类有几个新属性 - 有没有办法强制从接口强制转换为实际实现?

http://www.malcolmgroves.com/blog/?p=500 说这是(新)在 Delphi 2010 中实现的,这强烈表明以前不可能。确实是这样,还是有我不熟悉的方法? RTTI,也许吧?

(我检查过,Delphi 5 编译器确实不允许if pScore is TOleScore then - 这里pScore 是我的pScore: IScore 参数,TOleScore 是实现类。)

【问题讨论】:

  • 不同的是我禁止触摸界面;另一个问题 AFAICT 中不存在该限制。

标签: delphi interface delphi-5


【解决方案1】:

我认为这两种方法都应该有效。


顺便说一句,有谁知道 Hallvard 是否仍然活跃?在过去的几年里我没有遇到过他。

【讨论】:

  • 是的,Hallvard 仍然很活跃,他只是不再写博客了
  • 标记为答案,因为我不想标记我的:)
  • @Marcel 谢谢!出于好奇,JEDI 版本与 Hallvard 的版本有何不同?
【解决方案2】:

感谢我的老板,答案是:使用非常有用的 JEDI 库,特别是 GetImplementorOfInterface method

【讨论】:

    【解决方案3】:

    我做“possible duplicate”问题的接受答案所做的事情:

    让对象实现IObject 接口:

    IObject = interface(IUnknown)
        ['{39B4F98D-5CAC-42C5-AF8D-0237C8EFBE4C}']
        function GetSelf: TObject;
    end;
    

    原来是这样:

    var
       thingy: IThingy;
       o: TOriginalThingy;
    
    begin
       o := (thingy as IObject).GetSelf as TOriginalThingy;
    

    更新:要明确这一点,您可以向现有对象添加一个新的接口

    现有对象:

    type
        TOriginalThingy = class(TInterfacedObject, IThingy)
        public
           //IThingy
           procedure DrinkCokeZero; safecall;
           procedure ExcreteCokeZero; cafecall;
        end;
    

    添加IObject 作为它公开的接口之一:

    type
        TOriginalThingy = class(TInterfacedObject, IThingy, IObject)
        public
           //IThingy
           procedure DrinkCokeZero; safecall;
           procedure ExcreteCokeZero; cafecall;
    
           //IObject - provides a sneaky way to get the object implementing the interface
           function GetSelf: TObject;
        end;
    
        function TOriginalThingy.GetSelf: TObject;
        begin
           Result := Self;
        end;
    

    典型用法

        procedure DiddleMyThingy(Thingy: IThingy);
        var
           o: TThingy;
        begin
           o := (Thingy as IObject).GetSelf as TThingy;
    
           o.Diddle;
        end;
    

    【讨论】:

    • 听起来 OP 不能改变实现接口的代码。
    • 是的,很遗憾我绝对不能触摸界面:(
    • @Warren 不,此代码适用于所有 Delphi 版本。
    • @David,Marcel:我假设您原来的 interface 已被锁定(因为接口本来就是这样)。您正在使用的 object 将实现 another 完全独立的接口。另一方面,如果正如大卫所读的那样,您不允许触摸任何 代码 - 那么这是一个不同的问题。
    • 嘿,看,这是让·克雷蒂安(Jean Chrétien)担任总理时编写的德尔福版本。
    猜你喜欢
    • 1970-01-01
    • 2013-01-21
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 2017-02-16
    • 2019-07-26
    • 1970-01-01
    • 2023-03-22
    相关资源
    最近更新 更多