<< Click to Display Table of Contents >> Reflection - Custom Attributes |
![]() ![]() ![]() |
Saída
Id -> cd_pessoa
Detalhes -> ds_pessoa
Descricao -> nm_pessoa
Atributos.cs
using System;
namespace ConsoleApplication10
{
// class auxiliar para tributo campo
public class CampoAttribute : Attribute
{
public CampoAttribute(string nome)
{
this.Nome = nome;
}
public string Nome { get; set; }
}
}
Pessoa.cs
using System.Collections;
using System.Reflection;
namespace ConsoleApplication10
{
class Pessoa
{
[Campo("cd_pessoa")]
public int Id { get; set; }
[Campo("nm_pessoa")]
public string Descricao { get; set; }
[Campo("ds_pessoa")]
public string Detalhes { get; set; }
public Hashtable GetCampos()
{
Hashtable tabela = new Hashtable();
MemberInfo[] members = typeof(Pessoa).GetMembers();
foreach (MemberInfo member in members)
{
object[] attributes = member.GetCustomAttributes(true);
if (member.MemberType == MemberTypes.Property && attributes.Length != 0)
{
//PropertyInfo p = (PropertyInfo)member;
foreach (object attribute in attributes)
{
CampoAttribute atributos = attribute as CampoAttribute;
if (atributos != null)
tabela.Add(member.Name, atributos.Nome);
}
}
}
return tabela;
}
}
}
Program.cs
using System;
using System.Collections;
namespace ConsoleApplication10
{
class Program
{
static void Main(string[] args)
{
Pessoa p = new Pessoa();
Hashtable tb = p.GetCampos();
foreach (DictionaryEntry Item in tb)
Console.WriteLine(Item.Key.ToString() + " -> " + Item.Value.ToString());
Console.ReadLine();
}
}
}