Skip to content

Instantly share code, notes, and snippets.

@Fhernd
Created June 7, 2014 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Fhernd/25a81da23689266599ae to your computer and use it in GitHub Desktop.
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#.
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