C#Generic包含Generic

时间:2016-03-30 21:49:20

标签: c# generics

是一种更改包含泛型成员的泛型类的约束的方法,以避免像这样的构造:

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; }
    ...
}

现在要创建一个队列我应该写:

var _queue = new CommunicationQueue<DataTag<Messages>, Messages>(10);

但这就是我想要的:

var _queue = new CommunicationQueue<DataTag<Messages>>(10);

1 个答案:

答案 0 :(得分:2)

首先,您打算继承"oauth2Permissions": [ { "adminConsentDescription": "Allow the application to store a refresh token on behalf of the signed-in user.", "adminConsentDisplayName": "Refresh tokens", "id": "3AGH4D29-B64A-4A9A-8DBC-5DB3C8BBBD75", "isEnabled": true, "type": "User", "userConsentDescription": "Allow the application to store a refresh token on your behalf.", "userConsentDisplayName": "Store refresh token", "value": "refresh_token" } ] 吗?

如果没有,那么您可以将DataTag<T>的定义更改为

CommunicationQueue