You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从IOrderedDictionary继承接口并实现该继承接口?附代码示例

关于Delphi中继承Spring.Collections.IOrderedDictionary接口的实现建议

先把你给出的代码整理完整,方便后续分析:

uses Spring.Collections;

type
  IAttributeCollection = interface(IOrderedDictionary<String,String>)
  end;

  INodeContents = interface(IAttributeCollection)
    function Test: Boolean;
  end;

  TAttributeCollection = class(TInterfacedObject, IAttributeCollection)
  private
    FAttributes: IAttributeCollection;
    function GetAttributes: IAttributeCollection;
  public
    constructor Create;
    property Attributes: IAttributeCollection read GetAttributes;
    // 需补充IOrderedDictionary<String,String>的方法实现
  end;

针对你的代码结构,我整理了几个关键的实现要点和可能踩坑的地方:

  • 避免循环初始化的风险
    你的类里声明了FAttributes: IAttributeCollection,如果构造函数里不小心创建TAttributeCollection实例赋值给它,会触发无限递归创建对象。正确的做法是用Spring.Collections中IOrderedDictionary的具体实现类TOrderedDictionary<String,String>来初始化:

    constructor TAttributeCollection.Create;
    begin
      inherited;
      FAttributes := TOrderedDictionary<String,String>.Create;
    end;
    
  • 必须实现继承接口的全部方法
    因为IAttributeCollection继承了IOrderedDictionary<String,String>,所以TAttributeCollection必须实现该泛型接口的所有方法。如果采用委托模式(把逻辑转发给内部的FAttributes),可以参考下面的示例写法:

    function TAttributeCollection.Add(const Key: String; const Value: String): Integer;
    begin
      Result := FAttributes.Add(Key, Value);
    end;
    
    function TAttributeCollection.ContainsKey(const Key: String): Boolean;
    begin
      Result := FAttributes.ContainsKey(Key);
    end;
    
    // 其余如Remove、Items、Count等方法都按此方式委托给FAttributes即可
    
  • INodeContents接口的扩展实现
    如果后续需要实现INodeContents接口,只需让类(或子类)同时实现该接口即可,比如:

    TNodeContents = class(TAttributeCollection, INodeContents)
    public
      function Test: Boolean;
    end;
    
    function TNodeContents.Test: Boolean;
    begin
      // 这里写你的自定义逻辑,比如判断属性集合是否为空
      Result := not Self.IsEmpty;
    end;
    
  • Attributes属性的设计考量
    如果你本身的TAttributeCollection就是IAttributeCollection的实现,那么Attributes属性返回内部的FAttributes是合理的(装饰器模式);但如果你的类本身要作为属性集合直接对外暴露,可能不需要这个属性,直接让类的接口方法对外提供服务即可。

内容的提问来源于stack exchange,提问作者Mno

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:13:23