感谢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);
GetName 也是如此:
// Get the method info for GetName (note the new[] {typeof(Type)} signifying the arg taken by GetName
var getNameMethodInfo = typeof(MyClass).GetMethod("GetName", new[] { typeof(Type)});
var mCallGetName = Expression.Call(getNameMethodInfo, paramExp);