Skip to main content
 首页 » 编程设计

c#之是否可以为 HashSet 设置泛型

2024年02月23日19mfrbuaa

如果可能的话,我想做这样的事情。

internal sealed class BufferPool<T, K> : K<Buffer<T>> 
{ 
    public BufferPool() : base() {} 
    //etc... 
} 

然后像这样调用这个类:

BufferPool<byte, HashSet> buffers; 
buffers = new BufferPool<byte, HashSet>(bufferCapacity); 

或

BufferPool<byte, List> buffers; 
buffers = new BufferPool<byte, List>(bufferCapacity); 

请您参考如下方法:

您不能从类型参数继承(参见 How to inherit from a generic parameter? )。您可以做的是将类型参数限制为有用的类型和普通构造函数,并在您的类中实例化一个实例:

internal sealed class BufferPool<T, K> : IEnumerable<T> where K : IEnumerable<T>, new() 
{ 
    K _bufferImpl = new K(); 
 
    public BufferPool() : base() { } 
    //etc... 
}