我创建了一个自定义属性类
[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;}
}
现在我想创建一个方法,将View Model作为参数并返回自定义属性列表,例如:
List<Format> MyFormatAttributes = GetFormatAttributes(typeof(GridTestData))
答案 0 :(得分:1)
由于您的属性不公开,因此您需要使用NonPublic
绑定标记来获取它们。然后,从属性中,您可以从所需的类型中获取所有属性。
var attrs = typeof(GridTestData)
.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance)
.Select(o => o.GetCustomAttribute<Format>());
答案 1 :(得分:0)
调用Type.GetProperties获取PropertyInfo的类型列表,为每个PropertyInfo获取getcustomattributes()
答案 2 :(得分:0)
创建一个这样的方法:
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>();