如何给实体类中的字段增加额外的属性,然后利用反射读取该额外属性值
如何给实体类中的字段增加额外的属性,然后利用反射读取该额外属性值!
首先想到的是用attribute
如:
class Model{
string imgUrl;
[Attribute(...)]
public string ImgUrl{get;set;}
之类的,,既然没有提供,那就重写,怎么个重写法呢?
} 实体类 额外属性
[解决办法]
可以的,你可以重写一个Attribute类
如:
public class Model
{
string imgUrl;
[PropertyMappingAttribute(IsCondition=true)]
public string ImgUrl { get; set; }
}
//
public class PropertyMappingAttribute : Attribute
{
[Description("是否是额外属性"),DefaultValue(true)]
public bool IsCondition
{
get;set;
}
}
Model m=new Model();
PropertyInfo[] pis = m.GetType().GetProperties();
foreach (PropertyInfo pi in pis)
{
PropertyMappingAttribute []attr = (PropertyMappingAttribute[])pi.GetCustomAttributes(typeof(PropertyMappingAttribute),true);
if (attr.Length != 0 && attr[0].IsCondition)
{
//额外属性
}
}