[英]How can I make this simple C# generics factory work?
I have this design: 我有这个设计:
public interface IFactory<T> {
T Create();
T CreateWithSensibleDefaults();
}
public class AppleFactory : IFactory<Apple> { ... }
public class BananaFactory : IFactory<Banana> { ... }
// ...
The fictitious Apple
and Banana
here do not necessarily share any common types (other than object
, of course). 这里虚构的Apple
和Banana
不一定共享任何常见类型(当然除了object
)。
I don't want clients to have to depend on specific factories, so instead, you can just ask a FactoryManager
for a new type. 我不希望客户端依赖于特定的工厂,因此您可以向FactoryManager
询问新类型。 It has a FactoryForType
method: 它有一个FactoryForType
方法:
IFactory<T> FactoryForType<T>();
Now you can invoke the appropriate interface methods with something like FactoryForType<Apple>().Create()
. 现在,您可以使用FactoryForType<Apple>().Create()
等方法调用相应的接口方法。 So far, so good. 到现在为止还挺好。
But there's a problem at the implementation level: how do I store this mapping from types to IFactory<T>
s? 但是在实现级别存在问题:如何将这种映射从类型存储到IFactory<T>
s? The naive answer is an IDictionary<Type, IFactory<T>>
, but that doesn't work since there's no type covariance on the T
(I'm using C# 3.5). 天真的答案是IDictionary<Type, IFactory<T>>
,但由于T
上没有类型协方差(我正在使用C#3.5),因此不起作用。 Am I just stuck with an IDictionary<Type, object>
and doing the casting manually? 我只是坚持使用IDictionary<Type, object>
并手动执行转换?
Unfortunately yes you are stuck with the manual casting. 不幸的是,你坚持手动铸造。 However this casting can be an implementation detail and not seen by the consumer. 然而,该铸造可以是实施细节而消费者不会看到。 For example 例如
public class FactoryMap {
private Dictionary<Type,object> _map = new Dictionary<Type,object>();
public void Add<T>(IFactory<T> factory) {
_map[typeof(T)] = factory;
}
public IFactory<T> Get<T>() {
return (IFactory<T>)_map[typeof(T)];
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.