Si utilizza Delegate.CreateDelegate
, ad esempio da MethodInfo
; qui di seguito, ho hard-coded, ma si può usare una logica, o Expression
, per ottenere il metodo di creazione effettiva:
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();
}
}
Per i metodi non statici, v'è un sovraccarico di Delegate.CreateDelegate
che accetta l'istanza di destinazione .
fonte
2009-03-18 13:53:18
Mark, in realtà non so cosa sia T. Se sapessi cos'è T, sarebbe facile. –
Intendi nel metodo non generico? Aggiornerò ... –
Ho modificato la domanda per meglio esprimere il mio problema. –