Si je comprends bien votre question, vous avez, en substance, les types suivants définis:
public class Qaz
{
public void Foo<T>(T item)
{
Console.WriteLine(typeof(T).Name);
}
}
public class Bar { }
Maintenant, vous donné avez une variable bar
défini comme tel:
var bar = typeof(Bar);
Vous souhaitez ensuite pouvoir appeler Foo<T>
, en remplaçant T
par votre variable d'instance bar
.
Voilà comment:
// Get the generic method `Foo`
var fooMethod = typeof(Qaz).GetMethod("Foo");
// Make the non-generic method via the `MakeGenericMethod` reflection call.
// Yes - this is confusing Microsoft!!
var fooOfBarMethod = fooMethod.MakeGenericMethod(new[] { bar });
// Invoke the method just like a normal method.
fooOfBarMethod.Invoke(new Qaz(), new object[] { new Bar() });
Enjoy!
Pouvez-vous montrer du code où vous essayez de l'utiliser? C'est définitivement possible, c'est donc probablement une erreur de syntaxe. – RPM1984