You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

99 lines
3.2 KiB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
  1. using Apewer.Internals;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Reflection;
  5. using System.Text;
  6. namespace Apewer
  7. {
  8. /// <summary>标题特性。</summary>
  9. [Serializable]
  10. [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]
  11. public class CaptionAttribute : Attribute
  12. {
  13. private string _title, _description, _remark;
  14. /// <summary></summary>
  15. public CaptionAttribute(string title = null, string description = null, string remark = null)
  16. {
  17. Title = title;
  18. Description = description;
  19. Remark = remark;
  20. }
  21. /// <summary></summary>
  22. public string Title
  23. {
  24. get { return _title; }
  25. set { _title = value ?? Constant.EmptyString; }
  26. }
  27. /// <summary></summary>
  28. public string Description
  29. {
  30. get { return _description; }
  31. set { _description = value ?? Constant.EmptyString; }
  32. }
  33. /// <summary></summary>
  34. public string Remark
  35. {
  36. get { return _remark; }
  37. set { _remark = value ?? Constant.EmptyString; }
  38. }
  39. /// <summary>从 <see cref="CaptionAttribute"/> 到 Boolean 的隐式转换,判断 <see cref="CaptionAttribute"/> 有效。</summary>
  40. public static implicit operator bool(CaptionAttribute instance) => instance != null;
  41. #region static
  42. static Dictionary<string, CaptionAttribute> _cache = new Dictionary<string, CaptionAttribute>();
  43. /// <summary>解析标题特性,默认使用缓存以提升性能。</summary>
  44. /// <remarks>若修改已缓存实例的属性值,则下次从缓存中获取实例时将带有新的属性值。</remarks>
  45. /// <returns>已存在的 <see cref="CaptionAttribute"/> 实例。</returns>
  46. public static CaptionAttribute Parse(Type type, bool useCache = true)
  47. {
  48. if (type == null) return null;
  49. var cacheKey = type.FullName;
  50. if (useCache)
  51. {
  52. var hint = null as CaptionAttribute;
  53. lock (_cache)
  54. {
  55. if (_cache.ContainsKey(cacheKey))
  56. {
  57. hint = _cache[cacheKey];
  58. }
  59. }
  60. if (hint != null) return hint;
  61. }
  62. var attributes = type.GetCustomAttributes(typeof(CaptionAttribute), false);
  63. if (attributes.LongLength < 1L) return null;
  64. var attribute = (CaptionAttribute)attributes[0];
  65. if (useCache)
  66. {
  67. lock (_cache)
  68. {
  69. if (!_cache.ContainsKey(cacheKey)) _cache.Add(cacheKey, attribute);
  70. }
  71. }
  72. return attribute;
  73. }
  74. /// <summary>解析标题特性,默认使用缓存以提升性能。</summary>
  75. /// <remarks>若修改已缓存实例的属性值,则下次从缓存中获取实例时将带有新的属性值。</remarks>
  76. /// <returns>已存在的 <see cref="CaptionAttribute"/> 实例。</returns>
  77. public static CaptionAttribute Parse<T>(bool useCache = true) => Parse(typeof(T), useCache);
  78. #endregion
  79. }
  80. }