Delphi中的.NET"Type"类替代方案

5 delphi delphi-2009

我想用Delphi(2009 - 所以我有通用字典类)写一些类似于C#代码的东西:

Dictionary<Type, Object> d = new Dictionary<Type, Object>();
d.Add(typeof(ISomeInterface), new SomeImplementation());
object myObject = d[typeof(ISomeInterface)];
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?

提前致谢,

斯托伊奇

Mas*_*ler 9

对于接口,您将需要使用PTypeInfo指针,该指针由编译器魔术函数TypeInfo返回.PTypeInfo在TypInfo单元中声明.

type
  TInterfaceDictionary = TObjectDictionary<PTypeInfo, TObject>;
var
  d: TInterfaceDictionary;
  myObject: TSomeImplementation;
begin
  d := TInterfaceDictionary.Create([doOwnsValues]);
  d.Add(TypeInfo(ISomeInterface), TSomeImplementation.Create());
  myObject = d[TypeInfo(ISomeInterface)];
end;
Run Code Online (Sandbox Code Playgroud)

当然,如果这是类而不是接口,您可以只使用TClass引用.


Uwe*_*abe 6

如果它实际上是一个TInterfaceDictionary,你可以像这样写:

type
  TInterfaceDictionary = TObjectDictionary<TGUID, TObject>;
Run Code Online (Sandbox Code Playgroud)

显然,这需要每个接口使用GUID.

由于一些编译魔术,你可以非常简单地使用它:

  d.Add(ISomeInterface, TSomeImplementation.Create());
Run Code Online (Sandbox Code Playgroud)

(梅森:对于劫持示例代码感到抱歉)