Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Reflection;
- [AttributeUsage(AttributeTargets.All, AllowMultiple = false)]//для созданя своего атрибута декроируем класс нашего атрибута атрибутом AttributeUsage
- class MyAttribute : System.Attribute // наследуемся от System.Attribute
- {
- private readonly string date;
- public string Date
- {
- get { return date; }
- }
- public MyAttribute(string date) //конструктор для ридонли (позиционные парметры атрибута)
- {
- this.date = date;
- }
- private int number;
- public int Number // свойство для именованного парметра атрибута
- {
- get { return number; }
- set { number = value; }
- }
- }
- [AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
- class My2Attribute : System.Attribute
- {
- public int ID { get; }
- public My2Attribute(int id)
- {
- id = ID;
- }
- public string Commentary { get; set; }
- }
- }
- namespace AttributeWork
- {
- [My("1/31/2008", Number = 1)]
- [My2(10, Commentary = "class Number = 1; 1/31/2008")]
- public class MyClass
- {
- [MyAttribute("2/31/2007", Number = 2)]
- [My2(11, Commentary = "method 1st comment 2/31/2007, Number = 2")]
- [My2(12, Commentary = "method 2nd comment 2/31/2007, Number = 2")]
- private void Method()
- {
- Console.WriteLine("MyClass.Method()\n");
- }
- }
- class Program
- {
- static void Main()
- {
- MyClass my = new MyClass();
- // Анализ атрибутов.
- Type type = typeof(MyClass); //получаем переменную типа type класса MyClass котрая все знает об этом классе(типе)
- // Анализ атрибутов типа.
- // Получаем все аттрибуты заданного типа MyAttribute где type помечен MyClass
- // (false - без проверки базовых классов).
- object[] attributes = type.GetCustomAttributes(false);// получаем массив атрибутов примененных к классу MyClass (Type type = typeof(MyClass))
- foreach (var attribute in attributes)//имя класса атрибута надо указывать тут полностью с постфиксом
- {
- if (attribute.GetType() == typeof(MyAttribute))
- {
- MyAttribute attributer = attribute as MyAttribute;
- if (attributer != null)
- {
- Console.WriteLine("Анализ типа : Number = {0},\n Date = {1},\n typeID = {2}",
- attributer.Number, attributer.Date, attributer.TypeId);
- }
- }
- if (attribute.GetType() != typeof(My2Attribute)) continue;
- {
- if(attribute is My2Attribute attributer)
- {
- Console.WriteLine(new string('-', 20));
- Console.WriteLine(
- $"TypeId {attributer.TypeId},\n comment: {attributer.Commentary},\n ID is {attributer.ID}");
- }
- }
- }
- // Анализ атрибутов метода.
- // Получаем public static метод - Method.
- MethodInfo method = type.GetMethod("Method"
- );
- // Получаем все аттрибуты заданного типа MyAttribute
- // (false - без проверки базовых классов).
- attributes = method.GetCustomAttributes(typeof(MyAttribute) , false) ;
- foreach (MyAttribute attribute in attributes)
- {
- Console.WriteLine("Анализ метода: Number = {0}, Date = {1}",
- attribute.Number, attribute.Date);
- }
- object[] attributes2 = method.GetCustomAttributes(typeof(My2Attribute), false);
- foreach (My2Attribute attribute in attributes2)
- {
- }
- // Delay.
- Console.ReadKey();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement