要获取属性的描述/注释,需要使用System.ComponentModel命名空间中的DescriptionAttribute。可以通过反射获取属性上的DescriptionAttribute,并获取其Description属性值。
首先,需要引入System.ComponentModel命名空间:
using System.ComponentModel;
然后,代码如下:
// 获取Class的Type对象
Type type = orderDto.GetType();
// 获取Class的所有公共属性
PropertyInfo[] properties = orderDto.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{//属性名string propertyName = property.Name;//属性值string propertyValue = property.GetValue(orderDto)?.ToString();//描述/注释DescriptionAttribute descriptionAttribute = (DescriptionAttribute)property.GetCustomAttribute(typeof(DescriptionAttribute));string propertyDescription = descriptionAttribute?.Description ?? propertyName; // 如果没有描述/注释,则使用属性名作为默认值}
这样,就可以根据属性上的描述/注释来显示属性名了。注意,要确保在定义OrderDto类的属性时,使用了DescriptionAttribute来指定描述/注释。
public class OrderDto
{[Description("系统编号")]public string SysCode { get; set; }[Description("方向")]public string Fangxiang { get; set; }// 其他属性...
}