反射实体,获取属性上特性信息

//自定义属性  
public class CoustomAttribute : Attribute { /// <summary> /// 是否是业务ID /// </summary> public bool Key { get; set; } /// <summary> /// 是否是自定义字段 /// </summary> public bool IsCustomColumn { get; set; } }

/// <summary> /// 获取model中有[Key]自定义属性的主键,如没有,则返回第一个属性 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="model"></param> /// <returns></returns> public PropertyInfo GetKeyProperty<T>(T model) { var pis = model.GetType().GetProperties(); foreach (var pi in pis) { var atrrs = pi.GetCustomAttributes(typeof(CoustomAttribute), true); if (atrrs != null && atrrs.Any()) { foreach (CoustomAttribute item in atrrs) { if (item.Key) { return pi; } } } } return null; }
原文地址:https://www.cnblogs.com/houzf/p/10234420.html