2011-04-18 71 views
2

我原來的問題與Constrain type to specific types基本相同。將公共財產約束爲清單中的特定類型<Type>

我期望完成的基本上是這個。

public List<Type> MyPublicProperty { get; set; } where T IMyCustomInterface 

現在閱讀上面的問題,我可以看到它顯然是不可能的。

爲了給你一個上下文的概念,我正在構建一個解析器,它被設計爲支持多種類型(假設它們實現了一個特定的接口),但是我沒有對它可能解析的數據類型做任何編譯類型的假設。它只是提供了一個支持的類型列表,並且應該能夠自動完成剩下的工作。

所以基本上我想知道的是什麼是替代(除了運行時類型檢查何時設置屬性)這樣的屬性(如果有的話)?

編輯:建議的解決方案似乎不工作。

我最終的代碼看起來像這樣:

public class CustomSerializableTypeList<T> : List<T> where T : ITcpSerializable 
{ 

} 

CustomSerializableTypeList<Type> myCustomTypes = new CustomSerializableTypeList<Type>(); 

而且收到以下錯誤:

The type 'System.Type' cannot be used as type parameter 'T' in the generic type or method 'CustomSerializableTypeList'. There is no implicit reference conversion from 'System.Type' to 'ITcpSerializable'.

的錯誤是非常合情合理的,一旦我看看,想想泛型實現,已建議。

必須有解決方法。

+0

怎麼樣公開名單 MyPublicProperty {獲得;組; } – MattDavey 2011-04-18 15:48:28

+0

請注意:我不想提供實現特定類型的實例列表。我期待提供一個實現特定接口的List * *類型*。 – 2011-04-19 03:54:18

回答

3

我想你會需要自己的列表實現,將包裝List<Type>。也許是這樣的:

public class TypeList<T> where T : class 
{ 
    private readonly List<Type> list = new List<Type>(); 

    public void Add(Type item) 
    { 
     if(!typeof(T).IsAssignableFrom(item)) 
     { 
      throw new InvalidOperationException(); 
     } 

     list.Add(item); 
    } 
} 

你可能會想實現IList<Type>,然後簡單地委託方法的list當然。

1

您可以定義從List<T>派生的新集合類型CustomList<T>,並添加類型約束,然後在您的類中使用此類替代List<Type>

public class CustomList<T> : List<T> where T : ICustomInterface { 
    ... 
} 
1

Please note: I am not looking to provide a List OF instances that implement a specific type. I am looking to provide a List OF Types that implement a specific interface.

沒有快速'n'簡單的方法來做到這一點。你必須實現自己的集合類,重寫add方法,然後檢查,看看是否類型實現了通過反射你的界面...

class myTypeCollection : List<System.Type> 
{ 
    override void Add(Type t) 
    { 
     if (t.GetInterface(typeof(MyCustomInterface)) == null) 
      throw new InvalidOperationException("Type does not implement MyCustomInterface"); 

     base.Add(t); 
    } 
} 
相關問題