martes, mayo 05, 2009

Obtener los campos de un assembly de .Net mediante Reflection

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void btnObtener_Click(object sender, EventArgs e)
{
// Obtener las clases que contiene determinado assembly
Assembly a = Assembly.LoadFile(this.txtAssemblyPath.Text);
Type[] mytypes = a.GetTypes();
BindingFlags flags = (BindingFlags.NonPublic | BindingFlags.Public |
BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly);

// Para cada clase, obtener sus campos
foreach (Type t in mytypes)
{
this.txtFields.Items.Add("-------------------------------------------");
this.txtFields.Items.Add("Type: " + t.Name);
this.txtFields.Items.Add("-------------------------------------------");

FieldInfo[] fi = t.GetFields(flags);
foreach (FieldInfo m in fi)
{
this.txtFields.Items.Add(m.Name + " (" + m.FieldType.FullName + ")");
}
}
}
}
}