views:

224

answers:

2

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

+8  A: 

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.

Mason Wheeler
Thanks, Mason. This is the solution I was looking for.Actualy I'm gonna create a simple implementation of the Registry design pattern and I want my code to look something like that:Registry.RegisterComponent<ISomeInterface>(TSomeImplementation.Create);//or maybe even: RegisterComponent<ISomeInterface>(TSomeImplementation);. . .ISomeInterface i := Registry.GetComponent<ISomeInterface>;@ Uwe Raabe: It is interesting to know that this is possible but in my case interfaces have no GUID.
As a side note, I was at the Delphi Live conference last month, and Barry Kelly gave a presentation on a new enhanced RTTI model that's supposed to be in Delphi 2010. It's a lot more complete than the existing function set, and a lot easier to work with.
Mason Wheeler
+6  A: 

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)

Uwe Raabe
Huh. I hadn't thought of that. Yeah, this'll work for interfaces with GUIDs, specifically.
Mason Wheeler