jump to navigation

foreach a generic list returned in a method by reflection October 3, 2019

Posted by juanpablo1manrique in SharePoint.
trackback

Un ejemplo bastante útil,

La definición del método en el .dll original

 

public List<CarroEntity> ObtenerCarros()
{
List<CarroEntity> list = new List<CarroEntity>();
list.Add(new CarroEntity() { Color = "Azul", Marca = "Mazda", Placa = "DSF450" });
list.Add(new CarroEntity() { Color = "Amarillo", Marca = "Renault", Placa = "ESF245" });
list.Add(new CarroEntity() { Color = "Verde", Marca = "Mercedes", Placa = "KLS435" });
list.Add(new CarroEntity() { Color = "GrisPlata", Marca = "BMW", Placa = "NBD645" });
list.Add(new CarroEntity() { Color = "Negro", Marca = "Mazda", Placa = "BGT845" });
list.Add(new CarroEntity() { Color = "Blanco", Marca = "Mazda", Placa = "BHT545" });
return list;

}

Llamar este método por reflection

 

Assembly asm = Assembly.LoadFrom(@"D:\MyCode\MyCode\JUAN.WinWPF\JUAN.Carros\bin\Debug\JUAN.Carros.dll");
Type t = asm.GetType("JUAN.Carros.CarrosBL"); 
var methodInfo = t.GetMethod("ObtenerCarros");
if (methodInfo == null)
{
throw new Exception("No such method exists.");
}
var objBLInstance = Activator.CreateInstance(t, null);
System.Collections.IEnumerable instances = (System.Collections.IEnumerable)methodInfo.Invoke(objBLInstance, null);

Type tEntity = asm.GetType("JUAN.Carros.CarroEntity");
var property = tEntity.GetProperty("Placa");
foreach (object obj in instances)
{
Console.WriteLine(property.GetValue(obj));
}
Console.ReadLine();

 

Saludos

Comments»

No comments yet — be the first.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: