Dominando Reflection em C#: Descoberta de Tipos em Runtime e Programação Dinâmica
Objetos Reflection obtêm informação de tipo em tempo de execução. Classes de metadados estão no namespace System.Reflection.
System.Reflection permite: obter informação da aplicação, adicionar dinamicamente tipos/valores/objetos.
Aplicações do Reflection
- Ver informação de atributos em runtime.
- Examinar tipos em assembly e instanciá-los.
- Late binding a métodos/propriedades.
- Criar novos tipos em runtime e executar tarefas.
Visualizando Metadados
Objeto MemberInfo de System.Reflection inicializado para descobrir atributos associados a classe:
System.Reflection.MemberInfo info = typeof(MyClass);
Exemplo
using System;
[AttributeUsage(AttributeTargets.All)]
public class HelpAttribute : System.Attribute
{
public readonly string Url;
public string Topic { get { return topic; } set { topic = value; } }
public HelpAttribute(string url) { Url = url; }
private string topic;
}
[HelpAttribute("Information on the class MyClass")]
class MyClass { }
namespace AttributeAppl
{
class Program
{
static void Main(string[] args)
{
System.Reflection.MemberInfo info = typeof(MyClass);
object[] attributes = info.GetCustomAttributes(true);
for (int i = 0; i < attributes.Length; i++)
Console.WriteLine(attributes[i]);
Console.ReadKey();
}
}
}
Saída: HelpAttribute
Exemplo Completo: Lendo Atributos DeBugInfo
using System;
using System.Reflection;
namespace BugFixApplication
{
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Constructor | AttributeTargets.Field | AttributeTargets.Method | AttributeTargets.Property, AllowMultiple = true)]
public class DeBugInfo : System.Attribute
{
private int bugNo;
private string developer;
private string lastReview;
public string message;
public DeBugInfo(int bg, string dev, string d)
{
bugNo = bg; developer = dev; lastReview = d;
}
public int BugNo { get { return bugNo; } }
public string Developer { get { return developer; } }
public string LastReview { get { return lastReview; } }
public string Message { get { return message; } set { message = value; } }
}
[DeBugInfo(45, "Zara Ali", "12/8/2012", Message = "Return type mismatch")]
[DeBugInfo(49, "Nuha Ali", "10/10/2012", Message = "Unused variable")]
class Rectangle
{
protected double length, width;
public Rectangle(double l, double w) { length = l; width = w; }
[DeBugInfo(55, "Zara Ali", "19/10/2012", Message = "Return type mismatch")]
public double GetArea() { return length * width; }
[DeBugInfo(56, "Zara Ali", "19/10/2012")]
public void Display()
{
Console.WriteLine("Length: {0}", length);
Console.WriteLine("Width: {0}", width);
Console.WriteLine("Area: {0}", GetArea());
}
}
class ExecuteRectangle
{
static void Main(string[] args)
{
Rectangle r = new Rectangle(4.5, 7.5);
r.Display();
Type type = typeof(Rectangle);
// Atributos da classe
foreach (Object attr in type.GetCustomAttributes(false))
{
DeBugInfo dbi = (DeBugInfo)attr;
if (dbi != null)
{
Console.WriteLine("Bug No: {0}", dbi.BugNo);
Console.WriteLine("Developer: {0}", dbi.Developer);
Console.WriteLine("Last Reviewed: {0}", dbi.LastReview);
Console.WriteLine("Remarks: {0}", dbi.Message);
}
}
// Atributos dos métodos
foreach (MethodInfo m in type.GetMethods())
{
foreach (Attribute a in m.GetCustomAttributes(true))
{
DeBugInfo dbi = (DeBugInfo)a;
if (dbi != null)
{
Console.WriteLine("Bug No: {0}, Method: {1}", dbi.BugNo, m.Name);
Console.WriteLine("Developer: {0}", dbi.Developer);
Console.WriteLine("Last Reviewed: {0}", dbi.LastReview);
Console.WriteLine("Remarks: {0}", dbi.Message);
}
}
}
Console.ReadLine();
}
}
}
Saída: Exibe atributos da classe e dos métodos GetArea e Display com detalhes do bug, desenvolvedor, data e observações.
Linguagem C
- C# Hello World – Criando Sua Primeira Aplicação C#
- Entendendo Palavras-chave e Identificadores em C#: Regras, Listas e Boas Práticas
- Domine Variáveis e Tipos de Dados Primitivos em C#: Guia Completo
- Operadores em C# – Guia Completo dos Operadores em C#
- Dominando Operadores Bitwise e Bit Shift em C#: Guia Abrangente
- Fundamentos de C#: Essenciais de Entrada e Saída
- Expressões, Instruções e Blocos em C#: Guia Completo com Exemplos Práticos
- Dominando Comentários em C#: Tipos, Boas Práticas e Documentação XML
- Instrução Break em C#: Como e Quando Usar
- Dominando a Instrução Continue em C#: Como Pular Iterações de Loop Eficazmente