[Obsolete] //标记已过时的元素 [Obsolete("此方法已经过期,请使用更好的方法")] //标记已过时元素,使用时的提示语句 VipAttribute特性使用时为[Vip] 其后缀Attribute框架会自动加上去 namespace 特性demo { /// <summary> /// 自定义了一个VIP的特性标签 /// </summary> [AttributeUsage(AttributeTargets.Class|AttributeTargets.Method,AllowMultiple=true,Inherited=true)] public class VipAttribute:Attribute { } /// <summary> /// 定义一个Fly的自定义特性标签,用来检查当前类的实体类中的Fly方法是否可以正常执行 /// </summary> public class FlyAttribute:Attribute { int maxHeight; public FlyAttribute(int maxHeight) { this.maxHeight = maxHeight; } public bool IsFlyAble(int targHeight) { return targHeight <= maxHeight; } } } 使用[Fly]特性: [Fly(100)] public string Fly() { return "飞行高度=" + Height; } private void button2_Click(object sender, EventArgs e) { Pig pig = new Pig() { Name = "大猪", Age = 18, Height = 100 }; //1.0 先获取pig对象的Fly方法上面的特性标签FlyAttribute,再调用Flyattribute中的isFlyAble判断当前高度是否合适飞行 //2.0 获取pig对象中的Fly方法上面的特性标签FlyAttribute FlyAttribute flyAttr = pig.GetType().GetMethod("Fly").GetCustomAttribute<FlyAttribute>(); if(flyAttr.IsFlyAble(pig.Height)) { MessageBox.Show(pig.Fly()); } else { MessageBox.Show("飞行高度超过安全距离100"); } }
发现园子里有篇非常棒的讲解特性的文章:http://www.cnblogs.com/xugang/archive/2011/01/06/1927619.html