【问题标题】:Delphi TList<T> genericsDelphi TList<T> 泛型
【发布时间】:2014-10-26 23:48:28
【问题描述】:

如果可能的话,有人可以向我解释一下,否则我完全误解了这个 Delphi 功能。

假设我有一个类,我创建了一些类,然后将它们添加到 ObjectList。通常我会这样做:

Type TMyClass = class(TObject)
  stuff: string;
..
end;

Var things: TObjectList;

things := TObjectList.Create;
things.Add(TMyClass.Create);

// now I want to access stuff, so I need to typecast the class
TMyClass(things[0]).stuff..

所以现在我的问题是,是否有可能以我可以做的方式声明列表.. things[0].stuff 并且仍然可以访问常用的 TObjectList 功能,如 .sort .indexof 等。 ? (没有为此创建一个特殊的类来模拟对象列表)

【问题讨论】:

    标签: delphi generics tlist


    【解决方案1】:

    您正在使用TObjectList from System.Contnrs,它管理指针列表。

    你想要TObjectList from System.Generics.Collections。我知道,使用相同的名称可能会有点混乱。

    Type TMyClass = class(TObject)
      stuff: string;
    ..
    end;
    
    Var things: TObjectList<TMyCLass>;
    
    things := TObjectList<TMyCLass>.Create;
    things.Add(TMyClass.Create);
    
    things[0].stuff..
    

    【讨论】:

    • 谢谢,这很有用。最后一件事,你能给我一个 IComparer 函数的例子,用于这种不同类型的 objectlist 吗?通常的功能不适用于此。 (对于.sort)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-06
    • 2017-09-05
    • 1970-01-01
    • 1970-01-01
    • 2011-08-13
    • 2015-07-06
    相关资源
    最近更新 更多