Created
June 7, 2014 06:08
-
-
Save Fhernd/25a81da23689266599ae to your computer and use it in GitHub Desktop.
Demostración de la investigación de atributos personalizados a través de reflection en C#.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
namespace Recetas.Cap03 | |
{ | |
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Assembly, | |
AllowMultiple = true, Inherited = false)] | |
public class AutorAttribute : Attribute | |
{ | |
private string organizacion; | |
private string nombre; | |
// Constructor público: | |
public AutorAttribute (string nombre) | |
{ | |
this.nombre = nombre; | |
organizacion = String.Empty; | |
} | |
// Accede y modifica el nombre de la organización: | |
public string Organizacion | |
{ | |
get | |
{ | |
return organizacion; | |
} | |
set | |
{ | |
organizacion = value; | |
} | |
} | |
// Propiedad de sólo lectura (campo opcional): | |
public string Nombre | |
{ | |
get | |
{ | |
return nombre; | |
} | |
} | |
} | |
[AutorAttribute("Edward")] | |
[AutorAttribute("Germán", Organizacion = "OrtizOL")] | |
public class Reporte { } | |
public sealed class ConsultaAutorAttribute | |
{ | |
public static void Main() | |
{ | |
// Obtención del tipo: | |
Type tipo = typeof (Reporte); | |
// Recuperación arreglo con los atributos aplicados a `Reporte`: | |
object[] atributos = tipo.GetCustomAttributes(typeof(AutorAttribute), true); | |
// Enumera los atributos aplicados a `Reporte`: | |
foreach (AutorAttribute atributo in atributos) | |
{ | |
Console.WriteLine ("Nombre: {0} - Organización: {1}", atributo.Nombre, atributo.Organizacion); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment