2011-09-30 20 views
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() 

有没有办法来完成这样的事情,而不需要重复集合元素类型的参数,并且不使用反射?

回答

2

不,在您的约束范围内是不可能的。 Open generic类型只能作为参数运行到typeof。他们不允许在你的来源的任何其他地方。

相关问题