如何获取属性属性列表

本文关键字:属性 列表 获取 何获取 | 更新日期: 2023-09-27 18:26:01

我创建了一个自定义属性类

        [System.AttributeUsage(System.AttributeTargets.Property)]
        public class Format : Attribute
        {
            public string           DisplayName { get; set; }
            public ColumnType       ColumnType  { get; set; }
            public double           Width       { get; set; }
            public bool             ReadOnly    { get; set; }
            public Format()
            {
                ReadOnly = true;
            }
        }

然后我在下面的ViewModel类中实现了这个自定义属性

        public class GridTestData
        {
            [Format(ColumnType = grdOpt.Column.ColumnType.BoundInteger, DisplayName = "Auto ID", ReadOnly = true)]
            int AutoID          {get; set;}
            [Format(ColumnType = grdOpt.Column.ColumnType.BoundString, DisplayName = "String", ReadOnly = true)]
            string String       {get; set;}
            [Format(ColumnType = grdOpt.Column.ColumnType.BoundInteger, DisplayName = "Integer", ReadOnly = true)]
            int? Integer        {get; set;}
            [Format(ColumnType = grdOpt.Column.ColumnType.BoundDouble, DisplayName = "Double", ReadOnly = true)]
            double? Double      {get; set;}
            [Format(ColumnType = grdOpt.Column.ColumnType.BoundBooleanTriState, DisplayName = "Boolean", ReadOnly = true)]
            bool? Boolean       {get; set;}
            [Format(ColumnType = grdOpt.Column.ColumnType.BoundDateTime, DisplayName = "Date Time", ReadOnly = true)]
            DateTime? DateTime  {get; set;}
        }

现在我想创建一个方法,它将在我的视图模型类中作为参数,并返回一个自定义属性列表,例如:

List<Format> MyFormatAttributes = GetFormatAttributes(typeof(GridTestData))

如何获取属性属性列表

由于您的属性不是公共的,因此需要使用NonPublic绑定标志来获取它们。然后,您可以从属性中获取所需类型的所有属性。

var attrs = typeof(GridTestData)
    .GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
    .Select(o => o.GetCustomAttribute<Format>());

调用Type.GetProperties获取类型上的PropertyInfo列表,对于每个PropertyInfo获取getcustomattributes()

创建这样的方法:

public static IList<Format> GetFormatAttributes<TViewModel>()
{
   return typeof(TViewModel)
    .GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
    .Select(t => t.GetCustomAttribute<Format>())
    .Where(a != null)
    .ToList();
}

并以这种方式使用:

var myFormatAttributes = GetFormatAttributes<GridTestData>();