我希望用Delphi(2009年版本,因此我拥有通用字典类)编写类似于以下C#代码的内容:
Dictionary<Type, Object> d = new Dictionary<Type, Object>();
d.Add(typeof(ISomeInterface), new SomeImplementation());
object myObject = d[typeof(ISomeInterface)];
有什么想法吗?
提前感谢,
Hristo
我希望用Delphi(2009年版本,因此我拥有通用字典类)编写类似于以下C#代码的内容:
Dictionary<Type, Object> d = new Dictionary<Type, Object>();
d.Add(typeof(ISomeInterface), new SomeImplementation());
object myObject = d[typeof(ISomeInterface)];
有什么想法吗?
提前感谢,
Hristo
对于接口,您需要使用一个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;
如果它确实是TInterfaceDictionary,你可以像这样编写:
type
TInterfaceDictionary = TObjectDictionary<TGUID, TObject>;
显然,每个接口都需要使用GUID。
由于一些编译器的魔法,您可以非常简单地使用它:
d.Add(ISomeInterface, TSomeImplementation.Create());
(Mason: 对于劫持示例代码,我感到抱歉)