0
我想为myInterface
做一个工厂类,但是我无法调用具体类的构造函数,因为工厂类必须使用特定参数T
。带泛型的C#工厂模式
有没有办法为通用接口创建工厂类?
简单的例子
interface myInterface<T>
{
void work(T input);
T getSomething();
}
class A : myInterface<int>
{
//implementation
}
class B : myInterface<someClass>
{
//implementation
}
interface Factory<R,T>
{
R Create(T type);
}
class myFactory<T> : Factory<myInterface<T>, string>
{
myInterface<T> Create(string type) {
if(type == "A")
//return new A object
if(type == "B")
//return new B object
//some default behavior
}
}
那么,是什么或者不这段代码呢?你的研究表明了什么?您需要将要返回的实例转换为适当的类型。 – CodeCaster