我有一个接口(interface) InterfaceBase
和一些从它派生的接口(interface) Interface1, Interface2
。接下来我有实现 InterfaceX
接口(interface)的类,而不是基础接口(interface)。
现在,我是泛型的初学者,很多新方法让我脑子一片困惑 :( 。我想创建工厂(静态类),我在其中调用类似的东西
Interface1 concrete1 = Factory.Get<Interface1>();
这是我的(示例)工厂实现,它不起作用:
public static class Factory {
public static T Get<T>() where T: InterfaceBase{
Type type = typeof(T);
//return new Concrete1() as T; // type T cannot be used with the as
//return new Concrete1() as type; //type not found
//return new Concrete1(); // cannot implicitly convert
//return new Concrete1() as InterfaceBase; //cannot convert IBase to T
//return new Concrete1() as Interface1; //cannot convert Interface1 to T
}
}
我想要实现的是对应用程序的其余部分隐藏类(它们是网络服务处理程序)以便轻松地交换它们。我想使用工厂,因为类将是单例,它们将存储在工厂内部的 Dictionary 中,因此工厂可以通过此方法将它们传播到应用程序中,但作为接口(interface)...... 也许我没有正确使用约束 我做错了什么吗?我的方法不好吗?可以有更好的东西吗,也许应该重新设计整个架构?更好地显示 architecture 的图表.工厂不在里面
最佳答案
我认为您正在寻找的是“穷人依赖注入(inject)”。我想您应该为此使用真正的 IoC 容器,有很多选项(Unity、CaSTLe Windsor、Ninject...)。
但无论如何,如果您坚持自己做,请按照@Sergey Kudriavtsev 的建议去做。只需确保为每个接口(interface)返回正确的具体类即可。像这样:
public interface InterfaceBase { }
public interface Interface1 : InterfaceBase { }
public interface InterfaceX : InterfaceBase { }
public class Concrete1 : Interface1 { }
public class ConcreteX : InterfaceX { }
public static class Factory
{
public static T Get<T>()
where T : InterfaceBase
{
if (typeof(Interface1).IsAssignableFrom(typeof(T)))
{
return (T)(InterfaceBase)new Concrete1();
}
// ...
else if (typeof(InterfaceX).IsAssignableFrom(typeof(T)))
{
return (T)(InterfaceBase)new ConcreteX();
}
throw new ArgumentException("Invalid type " + typeof(T).Name, "T"); // Avoids "not all code paths return a value".
}
}
然后您通过将接口(interface)引用传递给工厂来调用它:
var instance = factory.Get<Interface1>();
关于c# - 从泛型方法返回对象作为接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9213313/