现有一个结构体
public struct Desc
{
private byte val1;
[Description("一个属性")]
public byte des
{
get { return val1; }
set { val1 = value; }
}
///...以下省略
}
获取Description代码:
string str = "";
Desc desc = new Desc();
不用反射 获取属性的特性
PropertyDescriptor pd = TypeDescriptor.GetProperties(typeof(Desc))["des"];
DescriptionAttribute description = pd == null ? null : pd.Attributes[typeof(DescriptionAttribute)] as DescriptionAttribute;
str = description == null ? "" : description.Description;
用反射 获取属性的特性
PropertyInfo pi = typeof(Desc).GetProperty("des");
foreach (object obj in pi.GetCustomAttributes(false))
{
if (obj is DescriptionAttribute)
str=(obj as DescriptionAttribute).Description;
}
不用反射 获取结构体的特性
AttributeCollection attributes = TypeDescriptor.GetAttributes(desc);//or typeof(Desc)
DescriptionAttribute da = (DescriptionAttribute)attributes[typeof(DescriptionAttribute)];
if(attributes.Contains(da))
str = da.Description;
用反射 获取结构体的特性
Type myType = typeof(Desc);
foreach (object obj in myType.GetCustomAttributes(false))
{
if (obj is DescriptionAttribute)
str = (obj as DescriptionAttribute).Description;
}