UnitComponentExtension.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Model;
  5. using MongoDB.Bson;
  6. namespace Controller
  7. {
  8. /// <summary>
  9. /// 控制复杂的unit逻辑,可以reload
  10. /// </summary>
  11. public static class UnitComponentExtension
  12. {
  13. public static void Add(this UnitComponent unitComponent, Unit unit)
  14. {
  15. unitComponent.units.Add(unit.Id, unit);
  16. if (!unitComponent.typeUnits.ContainsKey(unit.Config.Type))
  17. {
  18. unitComponent.typeUnits.Add(unit.Config.Type, new Dictionary<ObjectId, Unit>());
  19. }
  20. unitComponent.typeUnits[unit.Config.Type].Add(unit.Id, unit);
  21. }
  22. public static Unit Get(this UnitComponent unitComponent, ObjectId id)
  23. {
  24. Unit unit = null;
  25. unitComponent.units.TryGetValue(id, out unit);
  26. return unit;
  27. }
  28. public static Unit[] GetOneType(this UnitComponent unitComponent, int type)
  29. {
  30. Dictionary<ObjectId, Unit> oneTypeUnits = null;
  31. if (!unitComponent.typeUnits.TryGetValue(type, out oneTypeUnits))
  32. {
  33. return new Unit[0];
  34. }
  35. return oneTypeUnits.Values.ToArray();
  36. }
  37. public static bool Remove(this UnitComponent unitComponent, Unit unit)
  38. {
  39. if (unit == null)
  40. {
  41. throw new ArgumentNullException("unit");
  42. }
  43. if (!unitComponent.units.Remove(unit.Id))
  44. {
  45. return false;
  46. }
  47. if (!unitComponent.typeUnits[unit.Config.Type].Remove(unit.Id))
  48. {
  49. return false;
  50. }
  51. return true;
  52. }
  53. public static bool Remove(this UnitComponent unitComponent, ObjectId id)
  54. {
  55. Unit unit = unitComponent.Get(id);
  56. if (unit == null)
  57. {
  58. return false;
  59. }
  60. return unitComponent.Remove(unit);
  61. }
  62. }
  63. }