Skip to main content

Reflection | C#

  • Reflection | C#
info

Usando Reflection podemos inspecionar o código em tempo de execução (runtime) e realizar tarefas como:

  • Obter metadados das propriedades e métodos;
  • Instanciar objetos;
  • Chamar métodos e alterar propriedades;
  • Compilar e executar código dinamicamente;

Reflection cache

using System;
using System.Collections.Concurrent;
using System.Reflection;

public class Pessoa
{
public string Nome { get; set; }
public int Idade { get; set; }

public void Apresentar()
{
Console.WriteLine($"Olá, meu nome é {Nome} e tenho {Idade} anos.");
}
}

public static class ReflectionCache
{
private static readonly ConcurrentDictionary<string, PropertyInfo> PropertyCache = new();
private static readonly ConcurrentDictionary<string, MethodInfo> MethodCache = new();

public static PropertyInfo GetProperty(Type type, string propertyName)
{
string key = $"{type.FullName}.{propertyName}";
return PropertyCache.GetOrAdd(key, _ => type.GetProperty(propertyName));
}

public static MethodInfo GetMethod(Type type, string methodName)
{
string key = $"{type.FullName}.{methodName}";
return MethodCache.GetOrAdd(key, _ => type.GetMethod(methodName));
}
}

public class Program
{
public static void Main()
{
// Criar uma instância da classe Pessoa
Pessoa pessoa = new Pessoa { Nome = "João", Idade = 30 };

// Usar Reflection Cache para acessar a propriedade "Nome"
PropertyInfo nomeProperty = ReflectionCache.GetProperty(typeof(Pessoa), "Nome");
Console.WriteLine($"Propriedade Nome: {nomeProperty.GetValue(pessoa)}");

// Usar Reflection Cache para acessar o método "Apresentar"
MethodInfo apresentarMethod = ReflectionCache.GetMethod(typeof(Pessoa), "Apresentar");
apresentarMethod.Invoke(pessoa, null);

// Alterar a propriedade "Nome" usando Reflection
nomeProperty.SetValue(pessoa, "Maria");
Console.WriteLine($"Novo Nome: {nomeProperty.GetValue(pessoa)}");

// Invocar o método novamente após a alteração
apresentarMethod.Invoke(pessoa, null);
}
}