一、使用步骤
1.创建缓存字典
代码如下:
/// <summary>
/// 字典缓存
/// </summary>
private static readonly ConcurrentDictionary<Type, Dictionary<string, string>> _propertyDict = new();
2.实现
代码如下:
public static Dictionary<string,string> GetPropertyNames<T>()
{
// 查询缓存
var propertyDic = _propertyDict.ContainsKey(typeof(T)) ? _propertyDict[typeof(T)] : new Dictionary<string, string>();
if (propertyDic.Count != 0)
return propertyDic;//有缓存就返回
PropertyInfo[] pis = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(it => it.GetCustomAttributes(typeof(DisplayNameAttribute), true).Length > 0).ToArray();
Dictionary<string, string> dic = new(pis.Length);//指定字典大小
for (int i = 0; i < pis.Length; i++)
{
dic.Add(pis[i].Name, pis[i].GetCustomAttribute<DisplayNameAttribute>().DisplayName);
}
_propertyDict[typeof(T)] = dic;
return dic;
}
3.调用
ReflectionUtil.GetPropertyNames<T>();//T是你需要获取的实体