ch3_02.cs

来自「《c#技术内幕代码》」· CS 代码 · 共 68 行

CS
68
字号
using System;
using System.Reflection;

[AttributeUsage(AttributeTargets.Class|AttributeTargets.Struct)]
public class Creator : System.Attribute 
{
   public Creator(string name, string date) 
   { 
      this.name = name; 
      this.date = date; 
      version = 0.1;
   }
   public void Dump()
   {
      Console.WriteLine("Name {0}", name );
      Console.WriteLine("Date {0}", date );
      Console.WriteLine("Version {0}", version );
   }
   string date;
   string name;
   public double version; // to illustrate how to use named attributes
   
}

[Creator("Matt Telles", "05/01/2001", version=1.1)] class ATestClass1
{
    ATestClass1()
    {
    }
}

[Creator("Irving Berlin", "04/01/2000", version=1.5)] class ATestClass2
{
    ATestClass2()
    {
    }
}

[Creator("Anonymous", "12/31/2000", version=2.5)] class ATestClass3
{
    ATestClass3()
    {
    }
}


class CH3_2
{
   public static void PrintAttributeInformation(Type classType)
   {
      Console.WriteLine("Attributes for class {0}", classType );
      object[] attr = classType.GetCustomAttributes();
      foreach ( object o in attr )
      {
         Console.WriteLine("Attribute {0}", o );
	 if ( o is Creator )
	    ((Creator)o).Dump();
      }
   }
   public static void Main()
   {
      PrintAttributeInformation( typeof(ATestClass1) );
      PrintAttributeInformation( typeof(ATestClass2) );
      PrintAttributeInformation( typeof(ATestClass3) );
   }
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?