一、建立一个自定义的Attribute类
注:类名+Attribute,类需要继承Attribute
/// <summary> /// 特性 /// </summary> public class SensitiveFileTypeAttribute : Attribute { /// <summary> /// 字段类型 /// </summary> public SensitiveFileTypeEnum FileType { get; set; } public SensitiveFileTypeAttribute(SensitiveFileTypeEnum fileType) { FileType = fileType; } } /// <summary> /// 字段类型枚举 /// </summary> public enum SensitiveFileTypeEnum { /// <summary> /// 单价 /// </summary> Price = 1, /// <summary> /// 金额 /// </summary> Amount = 2, /// <summary> /// 折扣 /// </summary> Discount = 3 }
二、简单在属性上面使用特性:
属性上面标注特性:[特性名(特性值)]
public class SaleSoDtlDto { /// <summary> /// 数量 /// </summary> public int Qty { get; set; } /// <summary> /// 折扣 /// </summary> [SensitiveFileType(SensitiveFileTypeEnum.Discount)] public decimal Discount { get; set; } /// <summary> /// 未税本币结算价 /// </summary> [SensitiveFileType(SensitiveFileTypeEnum.Price)] public decimal SettlementPrice { get; set; } /// <summary> /// 含税本币结算金额 /// </summary> [SensitiveFileType(SensitiveFileTypeEnum.Amount)] public decimal TaxSettlementAmount { get; set; } }
三、获取某一个类上面有某特性的所有属性:
/// <summary> /// 导出敏感字段 /// </summary> public static class SensitiveFileAppService { /// <summary> /// 使用反射找出某一个类有标记某特性的属性 /// </summary> /// <typeparam name="T"></typeparam> public static List<PropertyInfo> GetSensitiveFileList<T>() where T : class, new() { List<PropertyInfo> proList = new List<PropertyInfo>(); var properties = typeof(T).GetProperties(); if (properties == null || !properties.Any()) return proList; foreach (PropertyInfo p in properties) { var name = p.Name;//属性名称 var attribute = p.GetCustomAttribute<SensitiveFileTypeAttribute>(); if (attribute == null) continue; //当前属性是否有SensitiveFileTypeAttribute特性 为NULL就没有此属性 var fileType = attribute.FileType;//特性的FileType属性值 proList.Add(p); } return proList; } }
public void TestWay() { var proList = SensitiveFileAppService.GetSensitiveFileList<SaleSoDtlDto>(); }
标签:SensitiveFileTypeEnum,set,Attribute,特性,用法,public,属性 From: https://www.cnblogs.com/yaoxiaodan/p/16906122.html