反射获取属性DisplayName特性名字以及属性值
程序员文章站
2022-10-01 10:35:44
/// /// 反射获取所有DisplayName标记值 /// /// 实体类型 /// 需要获取的实体 /// List GetDisplayName(T model) { //获取所有属性 PropertyInfo[] pr... ......
/// <summary> /// 反射获取所有displayname标记值 /// </summary> /// <typeparam name="t">实体类型</typeparam> /// <param name="model">需要获取的实体</param> /// <returns></returns> list<string> getdisplayname<t>(t model) { //获取所有属性 propertyinfo[] properties = model.gettype().getproperties(); var list = new list<string>(); foreach (var item in properties) { var attrs = item.getcustomattributes(typeof(displaynameattribute), true); if (attrs != null) { var displayname = ((displaynameattribute)attrs[0]).displayname; list.add(displayname); } } return list; } /// <summary> /// 反射获取属性值 /// </summary> /// <typeparam name="t">实体类型</typeparam> /// <param name="modellist">需要获取value的实体集合</param> /// <returns></returns> list<string> getvalue<t>(t modellist) { var list = new list<string>(); var type = modellist.gettype(); var properties = type.getproperties(); foreach (var item in properties) { var pname = item.name; propertyinfo propertyinfo = type.getproperty(pname); var value = propertyinfo.getvalue(modellist)?.tostring(); list.add(value); } return list; }