Data hosted with ♥ by Pastebin.com - Download Raw - See Original
  1. using System;
  2.  
  3. namespace Recetas.Cap03
  4. {
  5.     [AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly,
  6.                 AllowMultiple = true, Inherited = false)]
  7.     public class AutorAttribute : Attribute
  8.     {
  9.         private string organizacion;
  10.         private string nombre;
  11.        
  12.         // Constructor público:
  13.         public AutorAttribute (string nombre)
  14.         {
  15.             this.nombre = nombre;
  16.             organizacion = String.Empty;
  17.         }
  18.        
  19.         // Accede y modifica el nombre de la organización:
  20.         public string Organizacion
  21.         {
  22.             get
  23.             {
  24.                 return organizacion;
  25.             }
  26.             set
  27.             {
  28.                 organizacion = value;
  29.             }
  30.         }
  31.        
  32.         // Propiedad de sólo lectura (campo opcional):
  33.         public string Nombre
  34.         {
  35.             get
  36.             {
  37.                 return nombre;
  38.             }
  39.         }
  40.     }
  41.    
  42.     [AutorAttribute("Edward")]
  43.     [AutorAttribute("Germán", Organizacion = "OrtizOL")]
  44.     public class Reporte { }
  45.    
  46.     public sealed class ConsultaAutorAttribute
  47.     {
  48.         public static void Main()
  49.         {
  50.             // Obtención del tipo:
  51.             Type tipo = typeof (Reporte);
  52.            
  53.             // Recuperación arreglo con los atributos aplicados a `Reporte`:
  54.             object[] atributos = tipo.GetCustomAttributes(typeof(AutorAttribute), true);
  55.            
  56.             // Enumera los atributos aplicados a `Reporte`:
  57.             foreach (AutorAttribute atributo in atributos)
  58.             {
  59.                 Console.WriteLine ("Nombre: {0} - Organización: {1}", atributo.Nombre, atributo.Organizacion);
  60.             }
  61.         }
  62.     }
  63. }