Advertisement
Guest User

атрибуты рефлексия метод

a guest
May 24th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 4.56 KB | None | 0 0
  1. using System;
  2. using System.Reflection;
  3.    [AttributeUsage(AttributeTargets.All, AllowMultiple = false)]//для созданя своего атрибута декроируем класс нашего атрибута  атрибутом AttributeUsage
  4.     class MyAttribute : System.Attribute // наследуемся от System.Attribute
  5.     {
  6.         private readonly string date;
  7.         public string Date
  8.         {
  9.             get { return date; }
  10.         }
  11.  
  12.         public MyAttribute(string date) //конструктор для ридонли (позиционные парметры атрибута)
  13.         {
  14.             this.date = date;
  15.         }
  16.  
  17.         private int number;
  18.         public int Number // свойство для именованного парметра атрибута
  19.         {
  20.             get { return number; }
  21.             set { number = value; }
  22.         }
  23.     }
  24.    
  25.     [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
  26.     class My2Attribute : System.Attribute
  27.     {
  28.         public int ID { get; }
  29.         public My2Attribute(int id)
  30.         {
  31.             id = ID;
  32.         }
  33.  
  34.         public string Commentary { get; set; }
  35.     }
  36. }
  37.  
  38.  
  39. namespace AttributeWork
  40. {
  41.     [My("1/31/2008", Number = 1)]
  42.     [My2(10, Commentary = "class Number = 1; 1/31/2008")]
  43.     public class MyClass
  44.     {
  45.         [MyAttribute("2/31/2007", Number = 2)]
  46.         [My2(11, Commentary = "method 1st comment 2/31/2007, Number = 2")]
  47.         [My2(12, Commentary = "method 2nd comment 2/31/2007, Number = 2")]
  48.         private void Method()
  49.         {
  50.             Console.WriteLine("MyClass.Method()\n");
  51.         }
  52.     }
  53.  
  54.     class Program
  55.     {
  56.         static void Main()
  57.         {
  58.             MyClass my = new MyClass();
  59.              
  60.  
  61.             // Анализ атрибутов.
  62.  
  63.             Type type = typeof(MyClass); //получаем переменную типа  type  класса MyClass котрая все знает об этом классе(типе)
  64.  
  65.             // Анализ атрибутов типа.
  66.  
  67.             // Получаем все аттрибуты заданного типа MyAttribute  где type помечен MyClass
  68.             // (false - без проверки базовых классов).
  69.             object[] attributes = type.GetCustomAttributes(false);// получаем массив атрибутов примененных к классу  MyClass (Type type = typeof(MyClass))
  70.  
  71.             foreach (var attribute in attributes)//имя класса атрибута надо указывать тут полностью  с постфиксом
  72.             {
  73.                 if (attribute.GetType() == typeof(MyAttribute))
  74.                 {
  75.                     MyAttribute attributer = attribute as MyAttribute;
  76.                     if (attributer != null)
  77.                     {
  78.                         Console.WriteLine("Анализ типа  : Number = {0},\n Date = {1},\n typeID = {2}",
  79.                             attributer.Number, attributer.Date, attributer.TypeId);
  80.                     }
  81.  
  82.                 }
  83.                 if (attribute.GetType() != typeof(My2Attribute)) continue;
  84.                 {
  85.                     if(attribute is My2Attribute attributer)
  86.                     {
  87.                 Console.WriteLine(new string('-', 20));
  88.  
  89.                         Console.WriteLine(
  90.                             $"TypeId {attributer.TypeId},\n comment: {attributer.Commentary},\n ID is {attributer.ID}");
  91.                     }
  92.                 }
  93.             }
  94.  
  95.            
  96.  
  97.             // Анализ атрибутов метода.
  98.  
  99.             // Получаем public static метод - Method.
  100.             MethodInfo method = type.GetMethod("Method"
  101.                 );
  102.  
  103.             // Получаем все аттрибуты заданного типа MyAttribute
  104.             // (false - без проверки базовых классов).
  105.  
  106.             attributes = method.GetCustomAttributes(typeof(MyAttribute) , false) ;
  107.            
  108.             foreach (MyAttribute attribute in attributes)
  109.             {
  110.                 Console.WriteLine("Анализ метода: Number = {0}, Date = {1}",
  111.                     attribute.Number, attribute.Date);
  112.             }
  113.  
  114.             object[] attributes2 = method.GetCustomAttributes(typeof(My2Attribute), false);
  115.             foreach (My2Attribute attribute in attributes2)
  116.             {
  117.                
  118.             }
  119.  
  120.             // Delay.
  121.             Console.ReadKey();
  122.         }
  123.     }
  124. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement