[英]C# Generic contains Generic
Is a way to change where constraint for generic class containing generic member to avoid constructions like this: 一种更改包含泛型成员的泛型类的约束的位置的方法,以避免这种构造:
var _queue = new CommunicationQueue<DataTag<Messages>, Messages>(10);
//this is what I would like:
//var _queue = new CommunicationQueue<DataTag<Messages>>(10);
public class CommunicationQueue<TU, T> where TU : DataTag<T>, new()
where T : struct
{
private readonly ConcurrentQueue<TU> _queue;
public int Limit { get; }
public CommunicationQueue(int queueSize)
{
Limit = queueSize;
_queue = new ConcurrentQueue<TU>();
}
internal void AddItem(T item)
{
_queue.Enqueue(new TU { RowData = item });
while (_queue.Count > Limit)
{
TU removed;
_queue.TryDequeue(out removed);
}
}
public IEnumerable<TU> GetLatestItems()
{
return _queue.Reverse().Take(Limit).ToArray();
}
}
public class DataTag<T> where T : struct
{
public DateTime Time { get; set; }
public T RowData { get; set;}
public DataTag()
{
Time = DateTime.Now;
}
public DataTag(T rowData) : this()
{
RowData = rowData;
}
}
public struct Messages
{
string Name { get; set; }
...
}
Now to create a queue I should write: 现在创建队列,我应该写:
var _queue = new CommunicationQueue<DataTag<Messages>, Messages>(10);
But this is what I would like: 但这就是我想要的:
var _queue = new CommunicationQueue<DataTag<Messages>>(10);
First of all, are you planning to inherit from DataTag<T>
? 首先,您是否打算从DataTag<T>
继承?
If not, then you could change the definition of CommunicationQueue
to 如果不是,则可以将CommunicationQueue
的定义更改为
public class CommunicationQueue<T>
where T : struct
{
private readonly ConcurrentQueue<DataTag<T>> _queue;
//....
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.