c# – 通用Func的執行時建立
我需要實現的方法:
object GetFactory(Type type);
該方法需要返回一個Func<T>其中typeparam’T’是’type’.
所以我的問題是我不知道如何建立一個Func<?>在執行時使用反射. Activator.CreateInstance不起作用,因為代理上沒有建構函式.
有任何想法嗎?
你使用Delegate.CreateDelegate,即從一個MethodInfo;在下面,我已經硬編碼,但是你可以使用一些邏輯或者表示式獲得實際的建立方法:
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(); } }
對於非靜態方法,Delegate.CreateDelegate存在接受目標例項的過載.
http://stackoverflow.com/questions/658316/runtime-creation-of-generic-funct