Attribute 自定义特性/自定义属性
Attribute
意义:
用于定义针对类型的描述,标识等信息
语法1:
定义特性类
public class 自定义特性类名Attribute : Attribute { // 特性类构造函数 public 自定义特性类名Attribute(特性类构造方法参数值Animal pet) { thePet = pet; } // 特性类内部实现.... }
语法2:
调用特性类型,并初始化构造函数
[自定义特性类名(特性类构造方法参数值实例化)] public class 基础类名{ [自定义特性类名(特性类构造方法参数值实例化)] public void 基础类方法名(){ } }
语法3:
获取基础类实例的类型
基础类实例的对象名testClass.GetType()
语法4:
获取基础类实例的类型的所有方法
实例的类型type.GetMethods()
语法5:
获取基础类实例的类型方法的所有特性,因为一个方法可能会有多个特性
Attribute.GetCustomAttributes(类型的方法mInfo)
语法6:
获取方法种标记的自定义特性类的特性,匹配自定义类型特性
方法其中一个特性attr.GetType() == typeof(自定义特性类AnimalTypeAttribute)
语法7:
获取自定义特性类的特性构造方法参数值
((AnimalTypeAttribute)attr).Pet
示例:
using System; using System.Reflection; /// <summary> /// 枚举 /// </summary> public enum Animal { // Pets. Dog = 1, Cat, Bird, } /// <summary> /// 自定义属性 /// </summary> public class AnimalTypeAttribute : Attribute { // 构造函数 public AnimalTypeAttribute(Animal pet) { thePet = pet; } // 参数值. protected Animal thePet; public Animal Pet { get { return thePet; } set { thePet = value; } } } // A test class where each method has its own pet. class AnimalTypeTestClass { [AnimalType(Animal.Dog)] public void DogMethod() { } [AnimalType(Animal.Cat)] public void CatMethod() { } [AnimalType(Animal.Bird)] public void BirdMethod() { } } class DemoClass { static void Main(string[] args) { AnimalTypeTestClass testClass = new AnimalTypeTestClass(); Type type = testClass.GetType(); // 获取类型中所有方法 foreach (MethodInfo mInfo in type.GetMethods()) { // 获取方法的所有特性 foreach (Attribute attr in Attribute.GetCustomAttributes(mInfo)) { // 获得匹配的特性 if (attr.GetType() == typeof(AnimalTypeAttribute)) // 获取特性的参数值 Console.WriteLine( "Method {0} has a pet {1} attribute.", mInfo.Name, ((AnimalTypeAttribute)attr).Pet); } } } } /* * 控制台输出: * Method DogMethod has a pet Dog attribute. * Method CatMethod has a pet Cat attribute. * Method BirdMethod has a pet Bird attribute. */

浙公网安备 33010602011771号