1
,我會盡可能地做到直截了當地。傳遞一個集合作爲一個類型參數的通用定義 - 或如何使用「列表<>」作爲類型參數
我希望能夠做這樣的事情:
var mylookup = new ModifiableLookup<MyClass, int, List<> >();
var myhashlookup = new ModifiableLookup<MyClass, int, HashSet<> >();
雖然有沿着這條線的通用類:
class ModifiableLookup<TKey, TElement, TElementCollection<> > : ILookup<TKey, TElement>
where TElementCollection<> : ICollection<TElement>, new()
{
private Dictionary<TKey, TElementCollection<TElement> > data;
/// ... so on and so forth
}
但很可惜,這不工作...
解決方法是重複類型參數:
var mylookup = new ModifiableLookup<MyClass, int, List<int> >();
///...
class ModifiableLookup<TKey, TElement, TElementCollection> : ILookup<TKey, TElement>
where TElementCollection : ICollection<TElement>, new()
有沒有辦法來完成這樣的事情,而不需要重複集合元素類型的參數,並且不使用反射?