Properties.cs 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. namespace EventBus
  2. {
  3. public sealed class Properties
  4. {
  5. internal Dictionary<string, string> Filter { get; set; } = new Dictionary<string, string>();
  6. public void Add(string name, string value)
  7. {
  8. if (Filter.TryGetValue(name, out string val)) Filter[name] = value;
  9. else Filter.Add(name, value);
  10. }
  11. public string this[string name]
  12. {
  13. get
  14. {
  15. if (Filter.ContainsKey(name)) return Filter[name];
  16. else return null;
  17. }
  18. set
  19. {
  20. if (!Filter.ContainsKey(name)) Filter.Add(name, value);
  21. else Filter[name] = value;
  22. }
  23. }
  24. public static Properties GetProperties(string prostr)
  25. {
  26. if (string.IsNullOrEmpty(prostr)) return Properties.Default;
  27. Properties properties = new Properties();
  28. try
  29. {
  30. foreach (var item in prostr.Split("\r\n"))
  31. {
  32. var v = item.Split(":");
  33. properties[v[0]] = v[1];
  34. }
  35. }
  36. catch
  37. {
  38. }
  39. return properties;
  40. }
  41. public bool TryGetValue(string name, out string value) => Filter.TryGetValue(name, out value);
  42. public int Count => Filter.Count;
  43. public void Remove(string name) => Filter.Remove(name);
  44. public void Clear() => Filter.Clear();
  45. public IEnumerable<string> Values => Filter.Values;
  46. public IEnumerable<string> Names => Filter.Keys;
  47. /// <summary>
  48. /// 比较两个属性是否相等
  49. /// </summary>
  50. /// <param name="properties"></param>
  51. /// <returns></returns>
  52. internal bool Contains(Properties properties)
  53. {
  54. if (properties == null) return false;
  55. if (properties.Count != Count) return false;
  56. foreach (var name in Names)
  57. {
  58. if (!Filter.TryGetValue(name, out string val)) return false;
  59. else if (!val.Contains(properties[name])) return false;
  60. }
  61. return true;
  62. }
  63. public override string ToString()
  64. {
  65. return string.Join("\r\n", Filter.Select(x => $"{x.Key}:{x.Value}"));
  66. }
  67. public static Properties Default => new Properties();
  68. }
  69. }