ObservableList.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Threading;
  5. namespace IFramework
  6. {
  7. /// <summary>
  8. /// 可观测List
  9. /// </summary>
  10. /// <typeparam name="T">Object</typeparam>
  11. public class ObservableList<T> : Unit, IList<T>, IList
  12. {
  13. #region 事件与变量定义
  14. private Action<int, T> onItemAdded;
  15. private Action<int, int, T> onItemMoved;
  16. private Action<int, T> onItemRemoved;
  17. private Action<int, T, T> onItemReplaced;
  18. private Action onItemCleared;
  19. private Action<IList, int> onRangeAdded;
  20. private Action<IList, int> onRangeRemoved;
  21. [NonSerialized]
  22. private Object syncRoot; //同步访问对象
  23. private Lazy<List<T>> _value = new Lazy<List<T>>(() => { return new List<T>(); });
  24. private IList<T> value { get { return _value.Value; } }
  25. #endregion
  26. #region 注册与移除监听方法
  27. /// <summary>
  28. /// 注册方法 添加一个元素
  29. /// </summary>
  30. /// <param name="action">
  31. /// action arg1 : the index of the added item <br/>
  32. /// 参数1为添加的元素的索引 <br/><br/>
  33. /// action arg2 : the added item <br/>
  34. /// 参数2为添加的元素,类型为<typeparamref name="T" />
  35. /// </param>
  36. public void SubscribeAddItem(Action<int, T> action)
  37. {
  38. onItemAdded += action;
  39. }
  40. /// <summary>
  41. /// 移除方法 添加一个元素
  42. /// </summary>
  43. /// <param name="action">
  44. /// action arg1 : the index of the added item <br/>
  45. /// 参数1为添加的元素的索引 <br/><br/>
  46. /// action arg2 : the added item <br/>
  47. /// 参数2为添加的元素,类型为<typeparamref name="T" />
  48. /// </param>
  49. public void UnSubscribeAddItem(Action<int, T> action)
  50. {
  51. onItemAdded -= action;
  52. }
  53. /// <summary>
  54. /// 注册方法 移动一个元素
  55. /// </summary>
  56. /// <param name="action">
  57. /// action arg1 : the old index of the moved item <br/>
  58. /// 参数1为元素移动前的索引 <br/><br/>
  59. /// action arg2 : the new index of the moved item <br/>
  60. /// 参数1为元素移动后的索引 <br/><br/>
  61. /// action arg3 : the added item <br/>
  62. /// 参数3为移动的元素,类型为<typeparamref name="T" />
  63. /// </param>
  64. public void SubscribeMoveItem(Action<int, int, T> action)
  65. {
  66. onItemMoved += action;
  67. }
  68. /// <summary>
  69. /// 移除方法 移动一个元素
  70. /// </summary>
  71. /// <param name="action">
  72. /// action arg1 : the old index of the moved item <br/>
  73. /// 参数1为元素移动前的索引 <br/><br/>
  74. /// action arg2 : the new index of the moved item <br/>
  75. /// 参数1为元素移动后的索引 <br/><br/>
  76. /// action arg3 : the added item <br/>
  77. /// 参数3为移动的元素,类型为<typeparamref name="T" />
  78. ///</param>
  79. public void UnSubscribeMoveItem(Action<int, int, T> action)
  80. {
  81. onItemMoved -= action;
  82. }
  83. /// <summary>
  84. /// 注册方法 移除一个元素
  85. /// </summary>
  86. /// <param name="action">
  87. /// action arg1 : the index of the removed item <br/>
  88. /// 参数1为移除的元素的索引 <br/><br/>
  89. /// action arg2 : the removed item <br/>
  90. /// 参数2为移除的元素,类型为<typeparamref name="T" />
  91. /// </param>
  92. public void SubscribeRemoveItem(Action<int, T> action)
  93. {
  94. onItemRemoved += action;
  95. }
  96. /// <summary>
  97. /// 移除方法 移除一个元素
  98. /// </summary>
  99. /// <param name="action">
  100. /// action arg1 : the index of the removed item <br/>
  101. /// 参数1为移除的元素的索引 <br/><br/>
  102. /// action arg2 : the removed item <br/>
  103. /// 参数2为移除的元素,类型为<typeparamref name="T" />
  104. /// </param>
  105. public void UnSubscribeRemoveItem(Action<int, T> action)
  106. {
  107. onItemRemoved -= action;
  108. }
  109. /// <summary>
  110. /// 注册方法 替换一个元素
  111. /// </summary>
  112. /// <param name="action">
  113. /// action arg1 : the index of the replaced item <br/>
  114. /// 参数1为被替换的元素的索引 <br/><br/>
  115. /// action arg2 : the old item which has been replaced <br/>
  116. /// 参数2为被替换的元素,类型为<typeparamref name="T" /> <br/><br/>
  117. /// action arg3 : the new item which replaced the old one <br/>
  118. /// 参数3为替换进来的元素,类型为<typeparamref name="T" />
  119. /// </param>
  120. public void SubscribeReplaceItem(Action<int, T, T> action)
  121. {
  122. onItemReplaced += action;
  123. }
  124. /// <summary>
  125. /// 移除方法 替换一个元素
  126. /// </summary>
  127. /// <param name="action">
  128. /// action arg1 : the index of the replaced item <br/>
  129. /// 参数1为被替换的元素的索引 <br/><br/>
  130. /// action arg2 : the old item which has been replaced <br/>
  131. /// 参数2为被替换的元素,类型为<typeparamref name="T" /> <br/><br/>
  132. /// action arg3 : the new item which replaced the old one <br/>
  133. /// 参数3为替换进来的元素,类型为<typeparamref name="T" />
  134. /// </param>
  135. public void UnSubscribeReplaceItem(Action<int, T, T> action)
  136. {
  137. onItemReplaced -= action;
  138. }
  139. /// <summary>
  140. /// 注册方法 清空元素
  141. /// </summary>
  142. /// <param name="action">none arg Action</param>
  143. public void SubscribeClearItem(Action action)
  144. {
  145. onItemCleared += action;
  146. }
  147. /// <summary>
  148. /// 移除方法 清空元素
  149. /// </summary>
  150. /// <param name="action">none arg Action</param>
  151. public void UnSubscribeClearItem(Action action)
  152. {
  153. onItemCleared -= action;
  154. }
  155. /// <summary>
  156. /// 注册方法 插入一个集合
  157. /// </summary>
  158. /// <param name="action">
  159. /// action arg1 : the list of the insert items<br/>
  160. /// 参数1为插入的IList列表对象 <br/><br/>
  161. /// action arg2 : the index of the insert items<br/>
  162. /// 参数2为插入开始时的索引
  163. /// </param>
  164. public void SubScribeAddRange(Action<IList, int> action)
  165. {
  166. onRangeAdded += action;
  167. }
  168. /// <summary>
  169. /// 移除方法 插入一个集合
  170. /// </summary>
  171. /// <param name="action">
  172. /// action arg1 : the list of the insert items<br/>
  173. /// 参数1为插入的IList列表对象 <br/><br/>
  174. /// action arg2 : the index of the insert items<br/>
  175. /// 参数2为插入开始时的索引
  176. /// </param>
  177. public void UnSubScribeAddRange(Action<IList, int> action)
  178. {
  179. onRangeAdded -= action;
  180. }
  181. /// <summary>
  182. /// 注册方法 删除多个元素
  183. /// </summary>
  184. /// <param name="action">
  185. /// action arg1 : the list of the deleted items<br/>
  186. /// 参数1为删除的IList列表对象 <br/><br/>
  187. /// action arg2 : the first index of the deleted items<br/>
  188. /// 参数2为删除时对应的索引
  189. /// </param>
  190. public void SubScribeRemoveRange(Action<IList, int> action)
  191. {
  192. onRangeRemoved += action;
  193. }
  194. /// <summary>
  195. /// 移除方法 删除多个元素
  196. /// </summary>
  197. /// <param name="action">
  198. /// action arg1 : the list of the deleted items<br/>
  199. /// 参数1为删除的IList列表对象 <br/><br/>
  200. /// action arg2 : the first index of the deleted items<br/>
  201. /// 参数2为删除时对应的索引
  202. /// </param>
  203. public void UnSubScribeRemoveRange(Action<IList, int> action)
  204. {
  205. onRangeRemoved -= action;
  206. }
  207. #endregion
  208. #region 接口实现
  209. /// <summary>
  210. /// 索引器
  211. /// </summary>
  212. /// <param name="index">索引</param>
  213. /// <returns></returns>
  214. public T this[int index]
  215. {
  216. get { return value[index]; }
  217. set
  218. {
  219. if (this.value.IsReadOnly)
  220. throw new NotSupportedException("ReadOnlyCollection");
  221. if (index < 0 || index >= this.value.Count)
  222. throw new ArgumentOutOfRangeException($"index:{index}");
  223. ReplaceItem(index, value);
  224. }
  225. }
  226. /// <summary>
  227. /// 数量
  228. /// </summary>
  229. public int Count
  230. {
  231. get { return value.Count; }
  232. }
  233. /// <summary>
  234. /// 只读
  235. /// </summary>
  236. public bool IsReadOnly
  237. {
  238. get { return value.IsReadOnly; }
  239. }
  240. /// <summary>
  241. /// 将对象添加到List末尾
  242. /// </summary>
  243. /// <param name="item">要添加到List末尾的对象</param>
  244. public void Add(T item)
  245. {
  246. int index = value.Count;
  247. Insert(index, item);
  248. }
  249. /// <summary>
  250. /// 移除List中的所有元素
  251. /// </summary>
  252. public void Clear()
  253. {
  254. if (value.IsReadOnly)
  255. throw new NotSupportedException("ReadOnlyCollection");
  256. if (value.Count > 0)
  257. {
  258. value.Clear();
  259. onItemCleared?.Invoke();
  260. }
  261. }
  262. /// <summary>
  263. /// 确定某元素是否在List中
  264. /// </summary>
  265. /// <param name="item">要在List中定位的对象</param>
  266. /// <returns>如果存在返回true,否则为false</returns>
  267. public bool Contains(T item)
  268. {
  269. return value.Contains(item);
  270. }
  271. /// <summary>
  272. /// 从目标数组的指定索引处开始将整个List复制到兼容的一维Array
  273. /// </summary>
  274. /// <param name="array">从List中复制的元素的目标一维Array</param>
  275. /// <param name="arrayIndex">array中从零开始的索引,从此处开始复制</param>
  276. public void CopyTo(T[] array, int arrayIndex)
  277. {
  278. value.CopyTo(array, arrayIndex);
  279. }
  280. /// <summary>
  281. /// 返回循环访问List的IEnumerator
  282. /// </summary>
  283. /// <returns>List的泛型枚举器</returns>
  284. public IEnumerator<T> GetEnumerator()
  285. {
  286. return value.GetEnumerator();
  287. }
  288. /// <summary>
  289. /// 搜索指定的对象,并返回整个List中第一个匹配项的从零开始的索引
  290. /// </summary>
  291. /// <param name="item">要在List中定位的对象</param>
  292. /// <returns>List中第一个匹配项的从零开始的索引,如果未匹配到则为-1</returns>
  293. public int IndexOf(T item)
  294. {
  295. return value.IndexOf(item);
  296. }
  297. /// <summary>
  298. /// 将元素插入List的指定索引处
  299. /// </summary>
  300. /// <param name="index">插入 item 的从零开始的索引</param>
  301. /// <param name="item">要插入的对象</param>
  302. public void Insert(int index, T item)
  303. {
  304. if (value.IsReadOnly)
  305. throw new NotSupportedException("ReadOnlyCollection");
  306. if (index < 0 || index > value.Count)
  307. throw new ArgumentOutOfRangeException($"index:{index}");
  308. value.Insert(index, item);
  309. onItemAdded?.Invoke(index, item);
  310. }
  311. /// <summary>
  312. /// 从List中移除特定对象的第一个匹配项
  313. /// </summary>
  314. /// <param name="item">要删除的对象</param>
  315. /// <returns>成功移除返回true,否则为false;如果未找到也返回false</returns>
  316. public bool Remove(T item)
  317. {
  318. if (value.IsReadOnly)
  319. throw new NotSupportedException("ReadOnlyCollection");
  320. int index = IndexOf(item);
  321. if (index < 0)
  322. return false;
  323. var result = value.Remove(item);
  324. if (result)
  325. {
  326. onItemRemoved?.Invoke(index, item);
  327. }
  328. return result;
  329. }
  330. /// <summary>
  331. /// 移除List的指定索引处的元素
  332. /// </summary>
  333. /// <param name="index">要移除的元素的从零开始的索引</param>
  334. public void RemoveAt(int index)
  335. {
  336. if (value.IsReadOnly)
  337. throw new NotSupportedException("ReadOnlyCollection");
  338. if (index < 0 || index >= value.Count)
  339. throw new ArgumentOutOfRangeException($"index:{index}");
  340. T item = value[index];
  341. value.RemoveAt(index);
  342. onItemRemoved?.Invoke(index, item);
  343. }
  344. /// <summary>
  345. /// 替换指定索引处的元素
  346. /// </summary>
  347. /// <param name="index">待替换元素的从零开始的索引</param>
  348. /// <param name="item">位于指定索引处的元素的新值</param>
  349. private void ReplaceItem(int index, T item)
  350. {
  351. var oldItem = value[index];
  352. value[index] = item;
  353. onItemReplaced?.Invoke(index, oldItem, item);
  354. }
  355. /// <summary>
  356. /// 列表对象释放时调用(继承自Unit)
  357. /// </summary>
  358. protected override void OnDispose()
  359. {
  360. value.Clear();
  361. onItemAdded -= onItemAdded;
  362. onItemMoved -= onItemMoved;
  363. onItemRemoved -= onItemRemoved;
  364. onItemReplaced -= onItemReplaced;
  365. onItemCleared -= onItemCleared;
  366. }
  367. int IList.Add(object value)
  368. {
  369. if (this.value.IsReadOnly)
  370. throw new NotSupportedException("ReadOnlyCollection");
  371. if (value == null && !(default(T) == null))
  372. throw new ArgumentNullException("value is null");
  373. try
  374. {
  375. Add((T)value);
  376. }
  377. catch (InvalidCastException e)
  378. {
  379. throw new ArgumentException("", e);
  380. }
  381. return this.Count - 1;
  382. }
  383. bool IList.Contains(object value)
  384. {
  385. if ((value is T) || (value == null && default(T) == null))
  386. {
  387. return Contains((T)value);
  388. }
  389. return false;
  390. }
  391. int IList.IndexOf(object value)
  392. {
  393. int index = -1;
  394. if ((value is T) || (value == null && default(T) == null))
  395. {
  396. index = IndexOf((T)value);
  397. }
  398. return index;
  399. }
  400. void IList.Insert(int index, object value)
  401. {
  402. if (this.value.IsReadOnly)
  403. throw new NotSupportedException("ReadOnlyCollection");
  404. if (value == null && !(default(T) == null))
  405. throw new ArgumentNullException("value is null");
  406. try
  407. {
  408. Insert(index, (T)value);
  409. }
  410. catch (InvalidCastException e)
  411. {
  412. throw new ArgumentException("", e);
  413. }
  414. }
  415. void IList.Remove(object value)
  416. {
  417. if (this.value.IsReadOnly)
  418. throw new NotSupportedException("ReadOnlyCollection");
  419. if ((value is T) || (value == null && default(T) == null))
  420. {
  421. Remove((T)value);
  422. }
  423. }
  424. object IList.this[int index]
  425. {
  426. get { return value[index]; }
  427. set
  428. {
  429. if (value == null && !(default(T) == null))
  430. throw new ArgumentNullException("value is null");
  431. try
  432. {
  433. this[index] = (T)value;
  434. }
  435. catch (InvalidCastException e)
  436. {
  437. throw new ArgumentException("", e);
  438. }
  439. }
  440. }
  441. bool IList.IsFixedSize
  442. {
  443. get
  444. {
  445. IList list = value as IList;
  446. if (list != null)
  447. {
  448. return list.IsFixedSize;
  449. }
  450. return list.IsReadOnly;
  451. }
  452. }
  453. bool IList.IsReadOnly
  454. {
  455. get
  456. {
  457. return value.IsReadOnly;
  458. }
  459. }
  460. object ICollection.SyncRoot
  461. {
  462. get
  463. {
  464. if (this.syncRoot == null)
  465. {
  466. if (value is ICollection c)
  467. {
  468. this.syncRoot = c.SyncRoot;
  469. }
  470. else
  471. {
  472. Interlocked.CompareExchange<Object>(ref this.syncRoot, new Object(), null);
  473. }
  474. }
  475. return this.syncRoot;
  476. }
  477. }
  478. bool ICollection.IsSynchronized
  479. {
  480. get { return false; }
  481. }
  482. void ICollection.CopyTo(Array array, int index)
  483. {
  484. if (array == null)
  485. throw new ArgumentNullException("array is null");
  486. if (array.Rank != 1)
  487. throw new ArgumentException("RankMultiDimNotSupported");
  488. if (array.GetLowerBound(0) != 0)
  489. throw new ArgumentException("NonZeroLowerBound");
  490. if (index < 0)
  491. throw new ArgumentOutOfRangeException($"index:{index}");
  492. if (array.Length - index < Count)
  493. throw new ArgumentException("ArrayPlusOffTooSmall");
  494. if (array is T[] tArray)
  495. {
  496. value.CopyTo(tArray, index);
  497. }
  498. else
  499. {
  500. Type targetType = array.GetType().GetElementType();
  501. Type sourceType = typeof(T);
  502. if (!(targetType.IsAssignableFrom(sourceType) || sourceType.IsAssignableFrom(targetType)))
  503. throw new ArgumentException("InvalidArrayType");
  504. if (!(array is object[] objects))
  505. throw new ArgumentException("InvalidArrayType");
  506. int count = value.Count;
  507. try
  508. {
  509. for (int i = 0; i < count; i++)
  510. {
  511. objects[index++] = value[i];
  512. }
  513. }
  514. catch (ArrayTypeMismatchException)
  515. {
  516. throw new ArgumentException("InvalidArrayType");
  517. }
  518. }
  519. }
  520. IEnumerator IEnumerable.GetEnumerator()
  521. {
  522. return ((IEnumerable)value).GetEnumerator();
  523. }
  524. #endregion
  525. #region 额外方法实现
  526. /// <summary>
  527. /// 将指定索引处的项移至列表中的新位置
  528. /// </summary>
  529. /// <param name="oldIndex">指定要移动的项的位置的从零开始的索引</param>
  530. /// <param name="newIndex">当前状态下指定项的新位置的从零开始的索引</param>
  531. public void Move(int oldIndex, int newIndex)
  532. {
  533. if (oldIndex < 0 || oldIndex >= value.Count)
  534. throw new ArgumentOutOfRangeException($"oldIndex:{oldIndex}");
  535. if (newIndex < 0 || newIndex >= value.Count)
  536. throw new ArgumentOutOfRangeException($"newIndex:{newIndex}");
  537. if (oldIndex == newIndex) return;
  538. T item = value[oldIndex];
  539. value.RemoveAt(oldIndex);
  540. value.Insert(newIndex, item);
  541. onItemMoved?.Invoke(oldIndex, newIndex, item);
  542. }
  543. /// <summary>
  544. /// 在List末尾处添加一个集合
  545. /// </summary>
  546. /// <param name="collection"></param>
  547. /// <exception cref="NotSupportedException">只读警告</exception>
  548. public void AddRange(IEnumerable<T> collection)
  549. {
  550. int index = value.Count;
  551. InsertRange(index, collection);
  552. }
  553. /// <summary>
  554. /// 从索引处插入一个集合
  555. /// </summary>
  556. /// <param name="index">索引</param>
  557. /// <param name="collection">集合</param>
  558. /// <exception cref="NotSupportedException">只读错误</exception>
  559. /// <exception cref="ArgumentOutOfRangeException">越界报错</exception>
  560. public void InsertRange(int index, IEnumerable<T> collection)
  561. {
  562. if (value.IsReadOnly)
  563. throw new NotSupportedException("ReadOnlyCollection");
  564. if (index < 0 || index > value.Count)
  565. throw new ArgumentOutOfRangeException($"index:{index}");
  566. (value as List<T>).InsertRange(index, collection);
  567. onRangeAdded?.Invoke(ToList(collection), index);
  568. }
  569. /// <summary>
  570. /// 从索引处删除对应数量的元素
  571. /// </summary>
  572. /// <param name="index">索引</param>
  573. /// <param name="count">数量</param>
  574. /// <exception cref="NotSupportedException">只读报错</exception>
  575. /// <exception cref="ArgumentOutOfRangeException">越界报错</exception>
  576. public void RemoveRange(int index, int count)
  577. {
  578. if (value.IsReadOnly)
  579. throw new NotSupportedException("ReadOnlyCollection");
  580. if (index < 0 || index >= value.Count)
  581. throw new ArgumentOutOfRangeException($"index:{index}");
  582. List<T> list = value as List<T>;
  583. List<T> deletedItems = list.GetRange(index, count);
  584. list.RemoveRange(index, count);
  585. onRangeRemoved?.Invoke(deletedItems, index);
  586. }
  587. /// <summary>
  588. /// IEnumerable to IList
  589. /// </summary>
  590. /// <param name="collection">IEnumerable Collection</param>
  591. /// <returns>IList Collection</returns>
  592. private IList ToList(IEnumerable<T> collection)
  593. {
  594. if (collection is IList list)
  595. return list;
  596. List<T> newList = new List<T>();
  597. newList.AddRange(collection);
  598. return newList;
  599. }
  600. #endregion
  601. }
  602. }