一个继承的接口能够作为TDictionary中的键吗?
//! Note the inheritance of the interfaces
ILoggingProvider = interface
procedure Log(AMessage : string);
end;
IHTTPLoggingProvider = interface(ILoggingProvider)
function Login(AUserName : string; APassword : string) : boolean
end;
ILiveLoggingProvider = interface(ILoggingProvider)
function ConnectMonitor : boolean
end;
var
loggers : TDictionary<ILoggingProvider,TObject>;
...
loggers.add(ILoggingProvider, TSomeLogger.Create());
loggers.add(IHTTPLoggingProvider , TSuperLogger.Create()); //fails!
loggers.add(ILiveLoggingProvider , TAnotherLogger.Create()); //fails!
... //and the use them selectively
if loggers.ContainsKey(IHTTPLoggingProvider ) then
loggers.Items[IHTTPLoggingProvider].Log('Good bye world!');
... //and like this
var
theLogger : IHTTPLoggingProvider;
if loggers.ContainsKey(IHTTPLoggingProvider ) then
begin
theLogger := IHTTPLoggingProvider(loggers.Items[IHTTPLoggingProvider]);
if theLogger.Login('billy', 'bones') then
theLogger.Log('some message');
end;
TDictionary<ILoggingProvider,TObject>
想要接口引用而不是接口。将TObject
强制转换为IHTTPLoggingProvider
非常可疑。值类型应该是一个接口。我认为应该将键设置为GUID。或者我理解错了吗? - David HeffernanTLoggers = TDictionary<TGUID,ILoggingProvider>
时,在构建“TLoggers”实例时会引发异常“无效类型转换”,而使用loggers:= TDictionary<TGUID,ILoggingProvider>.Create
则正常运行。 有什么想法吗? - MX4399