C#的自定义属性就是Java中的Metadata,最近一直在鼓捣自己的C#的持久化架构,用到了对表中的字段标示,于是用了Java中Hibernate的解决办法,加入了自定义属性到持久化类的属性上,用于查询时候获得字段以及表的名称进行对应,代码如下:
1.声明自定义属性:
[AttributeUsage(AttributeTargets.Property,Inherited=true,AllowMultiple=false)] public class SelectParameterAttribute : Attribute { private string parameter; public SelectParameterAttribute(string param) { this.parameter = param; } public string GetParameter() { return this.parameter; } }
2.使用自定义属性定义实体类
public class Area { [SelectParameterAttribute("@Identifier")] public int Identifier { get; set; } [SelectParameterAttribute("@AreaName")] public string AreaName { get;set;} }
3.获得自定义属性:
Area area = new Area(); PropertyInfo prop = typeof(Area).GetProperty("Identifier"); Object[] objs=prop.GetCustomAttributes(true); //Console.Write(); //Object[] attrs =typeof(Area).GetCustomAttributes(true); Console.Write("objs:{0}",attrs.Length); foreach (Object attr in attrs) { if (attr is SelectParameterAttribute) { SelectParameterAttribute a = (SelectParameterAttribute)attr; Console.Write("param:{0}",a.GetParameter()); } }