在使用处引入包using System.ComponentModel;
在类成员前添加特性,如
public class A{
[Description("姓名")]
public string name {get;set;}
}
使用时
//获取类A的元数据数组
System.Reflection.PropertyInfo[] propertyInfos = typeof(A).GetProperties()
foreach(var item in propertyInfos ){
//获取成员描述
DescriptionAttribute customAttribute = (DescriptionAttribute)Attribute.GetCustomAttribute(item, typeof(DescriptionAttribute));
//name值为姓名
string name = customAttribute.Description;
}
C#反射与特性应用
本文介绍如何在C#中使用反射和特性来获取类成员的元数据,通过实例展示了如何定义并应用自定义特性,然后利用反射读取这些特性信息。
1万+

被折叠的 条评论
为什么被折叠?



