C# attribute属性的例子
来源:互联网 发布:心事谁人知 黄乙玲 编辑:程序博客网 时间:2024/05/29 04:45
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Reflection;namespace ConsoleApplication1{ //输出student类定义上的attribute信息和student的属性和方法上的attribute定义信息 [AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)] class StudentAttribute : Attribute { public StudentAttribute() { } //構造函數 private string name; private int age; private string privilege; private string description; /// <summary> /// 姓名 /// </summary> public string Name { get { return name; } set { name = value; } } /// <summary> /// 年齡 /// </summary> public int Age { get { return age; } set { age = value; } } /// <summary> /// 優先級 /// </summary> public string Privilege { get { return privilege; } set { privilege = value; } } /// <summary> /// 描述 /// </summary> public string Description { get { return description; } set { description = value; } } } [Student(Name = "Locus", Age = 29)] class Student { //private类型的属性不能读取 [Student(Description = "studentName")] private string Name; private string stuClass; //为属性添加说明 [Student(Description = "studentClass", Name = "studentClass1")] public string StuClass { get { return stuClass; } set { stuClass = value; } } [Student(Description = "studentRead")] //为方法添加说明 public void ReadBook() { Console.WriteLine("Student read book"); } } class Program { static object[] objs; static StudentAttribute sat; static void Main(string[] args) { var attrs = typeof(Student).GetCustomAttributes(typeof(StudentAttribute), true); Console.WriteLine((attrs[0] as StudentAttribute).Age); Console.WriteLine((attrs[0] as StudentAttribute).Name); PropertyInfo[] propArray = null; MethodInfo[] methodArray=null; propArray = typeof(Student).GetProperties(); methodArray=typeof(Student).GetMethods(); if (propArray.Length <= 0) Console.WriteLine("None PropertyInfo"); else foreach (PropertyInfo prop in propArray) { objs = prop.GetCustomAttributes(false); for (int i = 0; i < objs.Length; i++) { sat = (StudentAttribute)objs[i]; Console.WriteLine(sat.Description); } } if (methodArray.Length <= 0) Console.WriteLine("None MethodInfo"); else foreach (MethodInfo method in methodArray) { objs = method.GetCustomAttributes(false); for (int i = 0; i < objs.Length; i++) { if (objs[i] is StudentAttribute) { sat = (StudentAttribute)objs[i]; Console.WriteLine(method.Name); Console.WriteLine(sat.Description); } } } if (typeof(Student).IsDefined(typeof(StudentAttribute),true)) { Console.WriteLine("使用了StudentAttribute属性"); } Console.ReadLine(); } }}