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.

81 lines
2.6 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. namespace Apewer.Source
  5. {
  6. /// <summary>索引。</summary>
  7. [Serializable]
  8. [AttributeUsage(AttributeTargets.Property, AllowMultiple = true, Inherited = true)]
  9. public sealed class IndexAttribute : Attribute, IToJson
  10. {
  11. PropertyInfo _property = null;
  12. ColumnAttribute _column;
  13. string _name = null;
  14. FieldOrder _order = FieldOrder.Ascend;
  15. /// <summary>索引名称。</summary>
  16. public string Name { get => _name; }
  17. /// <summary>排序。</summary>
  18. public FieldOrder Order { get => _order; set => _order = value; }
  19. /// <summary>列。</summary>
  20. public ColumnAttribute Column { get => _column; }
  21. /// <summary>属性。</summary>
  22. public PropertyInfo Property { get => _property; }
  23. /// <summary>表示此属性是索引的一部分。</summary>
  24. /// <param name="name">索引名称。</param>
  25. public IndexAttribute(string name)
  26. {
  27. if (string.IsNullOrEmpty(name)) throw new ArgumentNullException(nameof(name));
  28. _name = name;
  29. }
  30. internal void SetColumn(ColumnAttribute column)
  31. {
  32. _column = column;
  33. }
  34. /// <summary>解析列的索引。</summary>
  35. /// <remarks>注意:此方法不再抛出异常,当不存在正确的列特性时将返回 NULL 值</remarks>
  36. public static IndexAttribute[] Parse(PropertyInfo property)
  37. {
  38. if (property == null) return null;
  39. var attributes = property.GetCustomAttributes(typeof(IndexAttribute), true);
  40. var ias = new List<IndexAttribute>();
  41. foreach (var attribute in attributes)
  42. {
  43. var ia = attribute as IndexAttribute;
  44. if (ia == null) continue;
  45. if (ia._name.IsEmpty()) continue;
  46. ia._property = property;
  47. ias.Add(ia);
  48. }
  49. return ias.ToArray();
  50. }
  51. /// <summary>生成 Json 对象。</summary>
  52. /// <exception cref="NotImplementedException"></exception>
  53. public Json ToJson()
  54. {
  55. var json = Json.NewObject();
  56. json.SetProperty("name", _name);
  57. json.SetProperty("order", _order.ToString());
  58. if (_column != null) json.SetProperty("column", _column.ToJson());
  59. return json;
  60. }
  61. /// <summary></summary>
  62. public override string ToString() => $"Index = {_name}, Field = {_column?.Field}, Order = {_order}";
  63. }
  64. }