C# 自定义特性
在C#中,自定义特性的创建用于将声明信息与代码(程序集、类型、方法、属性等)相关联,以任何需要的方式。特性增强了.NET的可扩展性能。
创建自定义特性的步骤:
1、定义一个自定义特性类,此特性类继承自System.Attribute类;
2、自定义特性类的命名以Attribute为后缀;
3、使用AttributeUsage特性来指定已创建的自定义特性类的使用范围;
4、创建自定义特性的构造函数和可访问属性;
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Drawing; 6 using System.Windows.Forms; 7 //C#项目展示自定义特性 8 9 namespace chen_customAttribute 10 { 11 //AttributeUsage 指定InformationAttribute的用法范围 12 [AttributeUsage(AttributeTargets.Class|AttributeTargets.Constructor|AttributeTargets.Method,AllowMultiple=true)] 13 //InformationAttribute是一个自定义特性类,继承自Attribute类 14 class InformationAttribute:Attribute 15 { 16 public string InformationString { get; set; } 17 } 18 //InformationAttribute用于student类 19 [Information(InformationString = "Class")] 20 public class student 21 { 22 private int rollno; 23 private string name; 24 25 [Information(InformationString = "Construtor")] 26 public student(int rollno, string name) 27 { 28 this.rollno = rollno; 29 this.name = name; 30 } 31 32 [Information(InformationString = "Method")] 33 public void display() 34 { 35 Console.WriteLine("Roll Number:{0}",rollno); 36 Console.WriteLine("Name:{0}",name); 37 } 38 } 39 40 public class GFG 41 { 42 public static void Main(string[] args) 43 { 44 student s = new student(1001,"Lily Adams"); 45 s.display(); 46 47 //通过.NET反射取出student的信息 48 System.Reflection.MemberInfo info = typeof(student); 49 InformationAttribute att = (InformationAttribute)Attribute.GetCustomAttribute(info,typeof(InformationAttribute)); 50 if (att != null) 51 { 52 Console.WriteLine("InformationAttribute特性的应用范围是:{0}",att.InformationString); 53 } 54 } 55 } 56 }