【问题标题】:List of interfaces with uncommon generic type具有不常见泛型类型的接口列表
【发布时间】:2016-01-11 10:49:25
【问题描述】:

我知道 Java 能够创建 for ex 的容器。通用接口 无需指定类型。这在 c# 中可能吗?

public interface Interface1<T>{
    void ProcessModel(T source);
}

public class Implement : Interface1<ModelClass>{
     .....implementation
}

我需要实例化一些像这样的容器

public List<Interface1> temp = new List<Interface1>();

不是这个

public List<Interface1<Implement>> temp = new List<Interface1<Implement>>();    

【问题讨论】:

  • 我能想到的唯一方法是包含列表的类本身是否是通用类。否则是不可能的,因为无法知道需要为所述类型分配多大的内存。
  • 或某种通用容器类,然后将其放入列表中。基础是非泛型的
  • 没有名为Interface1的接口。它不存在。只有Interface1&lt;T&gt;Interface1&lt;Type1&gt;Interface1&lt;Type2&gt; 是不同的类型。 (与 Java 相比, Interface1 存在)一种解决方案是让Interface1&lt;T&gt; 扩展另一个(非通用)接口并制作一个列表。

标签: java c# generics interface containers


【解决方案1】:

您可以简单地创建一个非泛型基接口,而不是为您的容器使用通用接口,该基接口扩展您的通用接口。现在您可以将所有这些衍生实例放入您的容器中:

interface IBase { }
interface IGenericInterface<T> : IBase { }
class MyClass : IGenericInterface<string> { }

class MyContainer {
    List<IBase> impl = new List<IBase>();

    void Main() {
        impl.Add(new MyClass());
    }
}

【讨论】:

    猜你喜欢
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-07
    • 1970-01-01
    • 1970-01-01
    • 2019-12-06
    相关资源
    最近更新 更多