Vous utilisez Delegate.CreateDelegate
, c'est-à-dire à partir d'un MethodInfo
; ci-dessous, je l'ai codé en dur, mais vous utiliseriez une certaine logique, ou Expression
, pour obtenir la méthode de création réelle:
using System;
using System.Reflection;
class Foo {}
static class Program
{
static Func<T> GetFactory<T>()
{
return (Func<T>)GetFactory(typeof(T));
}
static object GetFactory(Type type)
{
Type funcType = typeof(Func<>).MakeGenericType(type);
MethodInfo method = typeof(Program).GetMethod("CreateFoo",
BindingFlags.NonPublic | BindingFlags.Static);
return Delegate.CreateDelegate(funcType, method);
}
static Foo CreateFoo() { return new Foo(); }
static void Main()
{
Func<Foo> factory = GetFactory<Foo>();
Foo foo = factory();
}
}
Pour les méthodes non statiques, il y a une surcharge de Delegate.CreateDelegate
qui accepte l'instance cible .
Mark, je ne sais pas vraiment ce qu'est T. Si je savais ce que T est, ce serait facile. –
Vous voulez dire dans la méthode non générique? Je vais mettre à jour ... –
J'ai modifié la question pour mieux indiquer mon problème. –