2015-10-04 47 views
3

如何做這樣的事情只接受類型,其中一些聲明接口

List<Type:IMyInterface> a = new List<Type:IMyInterface>; 
a.Add(typeof(MyClass1)); //MyClass1..3 implementing IMyInterface 
a.Add(typeof(MyClass2)); 
a.Add(typeof(MyClass3)); 
IMyInterface c = default(a[1]); //create MyClass2 object 
a.Add(typeof(Object)); //must fail 

不首先建立目標或更高版本檢查類型?

+0

默認(A [1])將始終返回'null',你需要更好地詳細說明用例。 –

+0

'default(Type t)'必須返回使用默認無參構造函數創建的對象(如果存在)。在我的情況下'Type t'可以是'typeof(MyClass1..3)'。 –

+0

什麼只應該接受類型,爲什麼?你想做什麼? –

回答

2

你可以做到這一點,如果你知道靜態涉及的類型:

public class TypeList<T> 
{ 
    private readonly List<Type> types = new List<Type>(); 
    public void Add<D>() where D : T, new() 
    { 
     this.types.Add(typeof(D)); 
    } 

    public T NewAt(int index) 
    { 
     return (T)Activator.CreateInstance(this.types[index]); 
    } 
} 

那麼你可以做:

var a = new TypeList<IMyInterface>; 
a.Add<MyClass1>(); 
a.Add<MyClass2>(); 
a.Add<MyClass3>(); 
IMyInterface c = a.NewAt(1); 
a.Add<object>(); //won't compile 
3

你想要什麼不是直接支持在C#中。因爲Constraints on Type參數只能在構造函數,繼承層次結構,接口實現等幾個方面得到滿足。 more details

,你可以用不同的方式做到這一點,但是在這種方法中,沒有編譯時錯誤:

公共接口IMyConstraint { 無效DO(); }

public class MyClass: IMyConstraint 
{ 
    public void Do() 
    { 
    } 
} 

// Inherit from the List class to add some functionality to it 
public class MyTypeList<T> : List<T> where T : System.Type 
{ 
    public MyTypeList() 
    { 

    } 

    // use new keyword to prevent client from using the List.Add method. 
    public new void Add(T type) 
    { 
     // here you check if the type is implementing the interface or not 
     if (!typeof(IMyConstraint).IsAssignableFrom(type)) 
     { 
      // if it dose not implement the interface just throw an exception 
      throw new InvalidOperationException(); 
     } 
     // call the original List.Add method    
     base.Add(type); 
    } 
} 
+0

謝謝你。這是完整的答案。 –