2016-01-11 25 views
1

我知道Java能夠創建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>>();  
+0

我能想到的唯一的辦法就是,如果包含列表類本身就是一個泛型類。否則,這是不可能的,因爲無法知道需要爲這種類型分配多大的分配。 – Neijwiert

+1

或者一些通用的容器類,然後放入列表中。基地是非通用的 – Neijwiert

+5

沒有稱爲'Interface1'的接口。它不存在。只有'Interface1 '。 'Interface1 '和'Interface1 '是不同的類型。 (與Java相比,只有*'Interface1'存在)一種解決方案是讓'Interface1 '擴展另一個(非通用)接口並製作一個List。 –

回答

2

而不是使用您的容器的通用接口,你可以簡單地創建一個非通用你的通用擴展的基礎接口。現在,你可以把所有這些dervied情況下進入你的容器:

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

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

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