【问题标题】:C#, can I declare a List<MyInterface<T>> of type Interface which has a generic type T? [duplicate]C#,我可以声明一个具有泛型 T 的接口类型的 List<MyInterface<T>> 吗? [复制]
【发布时间】:2020-01-16 19:16:44
【问题描述】:

我想做一些我在 Java 中做过的事情。 我有一个通用类型的接口,例如:

interface IDAO<T>
{
   void Save(T data);
}

我有两个实现这个接口的类:

class BankAccountDAO : IDAO<BankAccount>
{
   public void Save(BankAccount data){...}
}

class CategoryDAO : IDAO<Category>
{
   public void Save(Category data) {...}
}

我需要另一个带有 List 的类,它应该声明为 IDAO 类型和泛型 T,以便我可以像这样将具体类添加到这个列表中:

class Manager
{
   private List<IDAO> daoList = new List<IDAO>(); // here is the error
   daoList.Add(new BankAccountDAO());
   daoList.Add(new CategoryDAO());

   public void myMethod(BankAccount b)
   {
      daoList.ElementAt(0).Save(b); // this should call the implemented Save() method of BankAccountDao
   }
}

我在 Java 中为一个项目执行此操作,但当我尝试在 C# 中执行此操作时出现错误:

CS0305 C# 使用泛型类型需要 1 个类型参数

有什么办法可以做这样的事情吗?

【问题讨论】:

  • 这是因为 C# 有真正的泛型而不是像 Java 这样的假泛型,所以 IDAO&lt;BankAccount&gt; 和 IDAO&lt;Category&gt; 是不同的类型
  • 为什么不用字典?或类似 DI 正在使用的东西......首先注册像 TypeFactory.Register&lt;IDAO&lt;BankAccount&gt;, BankAccountDAO&gt;() 或 TypeFactory.Register&lt;IDAO&lt;BankAccount&gt;&gt;(new BankAccountDAO()) 然后使用 TypeFactory.Resolve&lt;IDAO&lt;BankAccount&gt;&gt;().Save(new BankAccount { ... })

标签: c# list generics interface generic-collections


【解决方案1】:

您需要在Manager 类中将类型参数传递给IDAO;为此,您需要某种与BankAccount 和Category 结合的类型;如果可能的话,我会声明一个名为 IBusinessObject 的接口,Category 和 BankAccount 实现:

class Manager
{
   private List<IDAO> daoList = new List<IDAO<IBusinessObject>>(); // add type parameter for IDAO
   daoList.Add(new BankAccountDAO());
   daoList.Add(new CategoryDAO());
   public void myMethod(IBusinessObject b) // has to be IBusinessObject; 
                                           //you'll need to cast the underlying 
                                       ///type to promote it to a BankAccount or Category.
   {
      daoList.ElementAt(0).Save(b); // this should call the implemented Save() method of BankAccountDao
   }
}

【讨论】:

    猜你喜欢
    • 2011-08-13
    • 2012-12-30
    • 2011-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多