An alternative to the .NET Type class in Delphi

I want to write in Delphi (2009 - so I have a generic dictionary class) something similar to this C # code:

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

Any ideas?

Thanks in advance,

Christo

+5
source share
2 answers

For interfaces, you'll want to use the PTypeInfo pointer, which is returned by the TypeInfo compiler magic function. PTypeInfo is declared in the TypInfo module.

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;

Of course, if these were classes instead of interfaces, you could just use the TClass link.

+9
source

If this is actually a TInterfaceDictionary, you can write it like this:

type
  TInterfaceDictionary = TObjectDictionary<TGUID, TObject>;

Obviously, this requires a GUID for each interface.

- :

  d.Add(ISomeInterface, TSomeImplementation.Create());

(: )

+6

All Articles