【问题标题】:Move objects between containers and lose the interface在容器之间移动对象并丢失接口
【发布时间】:2012-02-21 15:57:08
【问题描述】:

假设我们有接口I、对象O和一个容器sl

type
  rootInterface = Interface
  end;

  childOfRootInterface = interface(rootInterface)
  end;

  ObjectImplementsRootInterface = class(TObject, I)
  end;

  ObjectImplementsChildOfRootInterface = class(TOtherObject, I2);
  end;

var
  aStringList: TStringList;

假设sl已初始化。

如果我们这样做

aStringList.Items.AddObject('root', ObjectImplementsRootInterface );

那我们做不到

ObjectImplementsRootInterface  := I(aStringList.Items.Objects([0]));

因为 Delphi 禁止这样做。如此尝试:

ObjectImplementsRootInterface  := TObject(aStringList.Items.Objects([0]));

但是,我们插入了一个childOfRootInterface,我们想要返回一个childOfRootInterface,所以我们这样做了

ObjectImplementsChildOfRootInterface  := childOfRootInterface (sl.Items.Objects([0]));

但是ObjectImplementsChildOfRootInterfaceObjectImplementsRootInterface有不同的supers!

虽然它们支持相同的界面,但我们无能为力。

在java中你可以传递对象,只要它们支持接口,在java中是可能的,所以现在经过所有这些规划;我可以在 Delphi 中做什么?

更新:更改了名称,但是该示例可能会克服我并获胜,找不到左右。

【问题讨论】:

    标签: delphi inheritance object interface


    【解决方案1】:

    干脆放弃了,并添加了另一个可以包含该 XML 的数据结构,并希望保留一个不能使用它们的不变量。

    【讨论】:

      【解决方案2】:

      这是一个工作代码示例:

      program Project9054004;
      
      {$APPTYPE CONSOLE}
      
      uses
        Classes, SysUtils, Dialogs;
      
      type  
        I = interface
        ['{6D39CF0A-839A-4DA3-B058-52E424702652}']
        end;
      
        O = class(TInterfacedObject, I)
        end;
      
      var
        SL: TStrings;
        TempO: O;
        TempI: I;
      begin
        ReportMemoryLeaksOnShutdown := True;
      
        SL := TStringlist.Create;
        try
          TempO := O.Create;
          SL.AddObject('a', TempO);
      
          if Supports(SL.Objects[0], I, TempI) then
          begin
            // use I
            TempI._AddRef;
            TempI._Release;
          end;
      
          ShowMessage(SL.Objects[0].ClassName);
      
        finally
          SL.Free;
        end;
      end.
      

      为了避免硬类型转换,我为界面使用了 GUID。

      支持可用于安全测试并将对象分配给类型 I 的变量。请注意,您的示例中的类型名称有点混乱。

      对象列表中的项目无法对接口进行硬类型转换。

      【讨论】:

      • 您的默认 Projects 目录中似乎有很多项目 (+1 :)
      • 这是 Stackoverflow 问题编号 ;)
      • 那会泄露的。您正在混合对象引用和接口引用。
      • 你应该因为声称我的命名约定是地狱而获得 +1。
      • 已更新,不再有内存泄漏和崩溃
      猜你喜欢
      • 2012-11-15
      • 1970-01-01
      • 1970-01-01
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-18
      相关资源
      最近更新 更多