Protocols.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Collections.Generic;
  4. using System.Diagnostics.Tracing;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. namespace WCS.Core
  9. {
  10. public class Protocols
  11. {
  12. protected static ConcurrentDictionary<Type, ConcurrentDictionary<string, ProtocolInfo>> ItemOfType = new ConcurrentDictionary<Type, ConcurrentDictionary<string, ProtocolInfo>>();
  13. public static bool HasProtocol(Type type, string code)
  14. {
  15. return ItemOfType[type].ContainsKey(code);
  16. }
  17. public static ProtocolInfo Get(Type type, string code)
  18. {
  19. ItemOfType[type].TryGetValue(code, out var info);
  20. return info;
  21. }
  22. /// <summary>
  23. /// 实例化Device,并未实例化Protocol
  24. /// </summary>
  25. /// <param name="world"></param>
  26. /// <returns></returns>
  27. public static List<Device> Generate(World world)
  28. {
  29. List<Device> list = new List<Device>();
  30. var gs = ItemOfType.SelectMany(v => v.Value.Select(d => new { code = d.Key, proto = d.Value, type = v.Key })).GroupBy(v=>v.code).ToList();
  31. foreach (var g in gs)
  32. {
  33. var dev = new Device { Code = g.Key, World = world };
  34. //foreach (var i in g)
  35. //{
  36. // //dev.Protocol(i.type);
  37. //}
  38. list.Add(dev);
  39. }
  40. return list;
  41. }
  42. }
  43. public class Protocols<T> : Protocols
  44. {
  45. static ConcurrentDictionary<string, ProtocolInfo> Items
  46. {
  47. get
  48. {
  49. if (!ItemOfType.TryGetValue(typeof(T), out var item))
  50. {
  51. item = new ConcurrentDictionary<string, ProtocolInfo>();
  52. ItemOfType[typeof(T)] = item;
  53. }
  54. return item;
  55. }
  56. }
  57. public static void Add(string code, ProtocolInfo info)
  58. {
  59. if (!Items.TryAdd(code, info))
  60. throw new Exception($"Protocols<{typeof(T)}>.Add()添加了重复的设备号");
  61. }
  62. public static ProtocolInfo Get(string code)
  63. {
  64. return Get(typeof(T), code);
  65. }
  66. }
  67. }