通用Func 的运行时创建
我需要实现这个方法:
object GetFactory(Type type);
此方法需要返回一个Func ,其中typeparam’T’是’type’。
所以,我的问题是我不知道如何使用reflection在运行时创建一个Func 。 Activator.CreateInstance不起作用,因为委托上没有构造函数。
有任何想法吗?
您使用Delegate.CreateDelegate
,即来自MethodInfo
; 下面,我已经硬编码,但你会使用一些逻辑或Expression
来获得实际的创建方法:
using System; using System.Reflection; class Foo {} static class Program { static Func GetFactory () { return (Func )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 factory = GetFactory (); Foo foo = factory(); } }
对于非静态方法, Delegate.CreateDelegate
的重载接受目标实例。
我认为通常的方法是让“哑”版本成为你在runtme上欺骗的东西,然后提供一个帮助扩展方法来提供类型安全的版本。
您可以创建Expression对象而不是func,并编译()表达式以获取Func委托。