要獲取屬性的描述/注釋,需要使用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; }// 其他屬性...
}