16-12-2010

.NET y Generics

Aveces, es necesario llamar a un método genérico teniendo como dato inicial un tipo Type.

Parece que la única manera de hacerlo es asi:

public class Ejemplo
{
public void Funcion(string s)
{
Console.WriteLine(string.Format("<{0}> -> {1}", typeof(T).Name, s));
}
}

class Program
{
static void Main(string[] args)
{
var c = new Ejemplo();
Type t = typeof (int);
var mInfo = typeof (Ejemplo).GetMethod("Funcion").MakeGenericMethod(t);
mInfo.Invoke(c, new object[]{"hola"});
}
}

0 comentarios: