Hristo
Hristo

Reputation:

The .NET 'Type' class alternative in Delphi

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

Upvotes: 5

Views: 463

Answers (2)

Uwe Raabe
Uwe Raabe

Reputation: 47819

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

type
  TInterfaceDictionary = TObjectDictionary<TGUID, TObject>;

Obviously this requires a GUID for each interface to use.

Due to some compiler magic you can use it quite simply:

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

(Mason: sorry for hijacking the sample code)

Upvotes: 6

Mason Wheeler
Mason Wheeler

Reputation: 84650

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.

Upvotes: 9

Related Questions