The .NET 'Type' class alternative in Delphi

delphi, delphi-2009

Solution

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

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 this was classes instead of interfaces, you could just use a TClass reference.

Problem

I want to write in Delphi (2009 - so I have generic dictionary class) something similar to that 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, Hristo

Original source