2012-11-07 30 views
3

我想創建一個類型列表,每個類型都必須實現一個特定的接口。像:在C#中創建一個類型列表

interface IBase { } 
interface IDerived1 : IBase { } 
interface IDerived2 : IBase { } 

class HasATypeList 
{ 
    List<typeof(IBase)> items; 
    HasATypeList() 
    { 
     items.Add(typeof(IDerived1)); 
    } 

} 

所以我知道我能做到

List<Type> items; 

但是,這不會限制在列表中允許的類型來實現IBASE的。我是否必須編寫自己的列表類?不,這是一個大問題,但如果我沒有......

+0

我以爲我有答案,但你是對的 - 你不想要的IBASE-實施對象,你想要的清單一個實現該接口的TYPE列表。我認爲你必須在增加 – n8wrl

回答

3

typeof(IBase)typeof(object)typeof(Foo),所有返回的Type實例,並用相同的成員等。

我不明白你想達到什麼目的,爲什麼你想區分這些?

事實上,代碼你寫在這裏:

List<typeof(IBase)> items; 

(我甚至不知道這編譯?) 是完全一樣的,因爲這:

List<Type> items; 

所以事實上,你試圖達到的是imho無用的。

如果你真的想達到這個目標 - 但我不明白爲什麼...... - ,你總是可以像Olivier Jacot-Descombes所建議的那樣創建自己的收藏類型,但在這種情況下,我寧願創建代替繼承自Collection<T>的類型:

public class MyTypeList<T> : Collection<Type> 
{ 
    protected override InsertItem(int index, Type item) 
    { 
     if(!typeof(T).IsAssignableFrom(item)) 
     { 
      throw new ArgumentException("the Type does not derive from ... "); 
     } 

     base.InsertItem(index, item); 
    } 
} 
+0

的基礎上實現你自己的列表和額外的邏輯。這基本上是我最終做的。我只是想知道是否有一個更聰明的方法來做到這一點。例如使用where子句或其他東西... – jackjumper

+0

而我不認爲它是無用的。我想要一個列表中的所有類型必須實現某個接口的類型列表。 – jackjumper

+0

你打算如何處理這個清單? –

1

是的。如果類型不是IBase的子類,則必須實現一個拋出異常的List。

沒有內置的方法來做你想做的。

1

做到這一點的唯一方法是創建自己的類型集合

public class MyTypeList 
{ 
    List<Type> _innerList; 

    public void Add(Type type) 
    { 
     if (typeof(IBase).IsAssignableFrom(type)) { 
      _innerList.Add(type); 
     } else { 
      throw new ArgumentException(
       "Type must be IBase, implement or derive from it."); 
     } 
    } 

    ... 
}