c# - 从泛型方法返回对象作为接口(interface)

标签 c# design-patterns architecture interface factory-method

我有一个接口(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/

相关文章:

c# - 如何根据类型列表检查对象的类型?

java - 设计模式——输入不同的对象,返回相同的对象

java - 我没有看到蝇量模式有任何用途。真的有用吗?

php - Laravel - 从自定义类重定向

c# - 将 xamarin 表单与 IServiceProvider 一起使用

c# - Entity Framework 中的多个 where 语句

c# - 在 C# 中,继承树可以达到多深?

c++ - 通过策略(策略)模式启用多个后端

ruby-on-rails - 如何在 Ruby on Rails 中构建多级层次结构?

c# - 将String解析为多个可变长度的String(C#)