mikhailemv

Untitled

Apr 22nd, 2023
1,032
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.44 KB | None | 0 0
  1. using System.Collections.Generic;
  2.  
  3. namespace rocket_bot
  4. {
  5.     public class Channel<T> where T : class
  6.     {
  7.         private readonly List<T> list = new List<T>();
  8.  
  9.         public T this[int index]
  10.         {
  11.             get
  12.             {
  13.                 lock (list)
  14.                 {
  15.                     return list.Count <= index || index < 0 ? null : list[index];
  16.                 }
  17.             }
  18.  
  19.             set
  20.             {
  21.                 lock (list)
  22.                 {
  23.                     if (Count > index && index >= 0)
  24.                     {
  25.                         list[index] = value;
  26.                         list.RemoveRange(index + 1, list.Count - index - 1);
  27.                     }
  28.  
  29.                     else if (index == list.Count)
  30.                         list.Add(value);
  31.                 }
  32.             }
  33.         }
  34.  
  35.         public T LastItem()
  36.         {
  37.             lock (list)
  38.             {
  39.                 return list.Count == 0 ? null : list[list.Count - 1];
  40.             }
  41.         }
  42.  
  43.         public void AppendIfLastItemIsUnchanged(T item, T knownLastItem)
  44.         {
  45.             lock (item)
  46.             {
  47.                 if (Equals(LastItem(), knownLastItem)) list.Add(item);
  48.             }
  49.         }
  50.  
  51.         public int Count
  52.         {
  53.             get
  54.             {
  55.                 lock (list)
  56.                 {
  57.                     return list.Count;
  58.                 }
  59.             }
  60.         }
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment