假设我有一个返回T的静态方法,如:
T myT = MyClass.Create(type); // type is System.Type
然后我希望能够构建和编译表达式,以便我可以拥有Func<T>
,但我无法弄清楚如何去做。
我可以为Constant
做:
Func<T> result = Expression.Lambda<Func<T>>(Expression.Constant(string.Empty)).Compile()
但对MyClass.Create(type)
我感到困惑。
Func<T> result = ....?
答案 0 :(得分:2)
感谢populate
的提示,我设法使用false
做了这样的话:
usr
然后:
Expression.Call
或者,而不是:
public static class MyClass
{
public static string GetTime()
{
return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss,fff");
}
public static string GetName(Type type)
{
return type.Name;
}
}
我们可以使用:
撰写// Calls static method GetTime with no args
var mCallGetTime = Expression.Call(typeof(MyClass), "GetTime", null);
Func<string> resultNoArg = Expression.Lambda<Func<string>>(mCallGetTime).Compile();
// The input param for GetName which is of type Type
var paramExp = Expression.Parameter(typeof(Type));
// Calls static method GetName passing in the param
var mCallGetName = Expression.Call(typeof(MyClass), "GetName", null, paramExp);
Func<Type, string> resultWithArg = Expression.Lambda<Func<Type, string>>(mCallGetName, paramExp).Compile();
// You can then call them like so... Print() just prints the string
resultNoArg().Print();
resultWithArg(typeof(string)).Print();
resultWithArg(typeof(int)).Print();
var mCallGetTime = Expression.Call(typeof(MyClass), "GetTime", null);
同样适用于Expression.Call
:
// Get the method info for GetTime (note the Type[0] signifying no args taken by GetTime);
var methodInfo = typeof(MyClass).GetMethod("GetTime", new Type[0]);
var mCallGetTime = Expression.Call(methodInfo);
答案 1 :(得分:1)
您的答案的另一种方法是创建一个完全通用的方法,为任何类型的任何泛型静态方法构造Func<T>
。
public Func<T> BuildGenericStaticFunc<T>()
{
var type = typeof(T);
return Expression.Lambda<Func<T>>(
Expression
.Call(
type.GetMethod("Create", BindingFlags.Static | BindingFlags.Public)
.MakeGenericMethod(type),
Expression.Constant(type)
))
.Compile();
}
var result = BuildGenericStaticFunc<MyClass>();