我有这个静态函数
public static object Create(Type t)
{
//unimportant
}
我无法控制上述功能,因此无法更改。问题是它不是通用的,所以我必须将返回的对象转换为某种类型。这种类型是由我调用该Create
方法的另一个泛型类的约束提供的。
这是我到达的地方:
public static class Creator<T>
{
public static void Create()
{
var m = typeof(SomeClass).GetMethod("Create");
var p = Expression.Parameter(typeof(Type));
var e = Expression.Call(m, p);
//at this stage I want to create delegate for calling the 'Create' method,
//then pass typeof(T) as parameter, get returned object,
//and finally cast it to 'T'.
//for eg, I can do it like this:
var f = Expression.Lambda<Func<Type, object>>(e, p).Compile();
Func<T> mainThing = () => (T)f(typeof(T));
//is there a way I can achieve in one step?
}
}
在我上面的方法中,我不是在编译最终的委托,而是在编译之前的一步。我如何在编译之前合并演员表并Func<T>
返回?