我有(例如) a ,Func<int, int>我想像往常一样调用它,除了参数的类型为objectratingr than int。我只知道 Func 的确切类型和运行时的参数,因为 Func 是使用表达式树创建的,现在可以从变量访问dynamic。(简化)代码示例:
using System.Linq.Expressions;
namespace FuncExample
{
class Program
{
static void Main(string[] args)
{
object myFunc = CreateFunc(); // Could return something like
// Func<int, int>, but may return a
// completely different Func<> depending on
// arguments etc.
object result = getFromFunc(5, myFunc);
}
public static object CreateFunc()
{
LambdaExpression expr = Expression.Lambda(
/*
* Create an expression
*/
);
return expr.Compile();
}
public static object getFromFunc(object arg, object func)
{
dynamic dynFunc = func;
return dynFunc(arg); // <------- Throws exception
}
}
}
Run Code Online (Sandbox Code Playgroud)
如何使代码转换arg为整数或参数的任何类型?我尝试创建一个通用方法,将对象转换为某种类型,然后通过反射调用它,如下所示:
public static T asT<T>(object n)
{
return (T)n;
}
Run Code Online (Sandbox Code Playgroud)
为了getFromFunc:
MethodInfo con = typeof(Program).GetMethod("asT").MakeGenericMethod(func.GetType().GetGenericArguments()[0]);
return dfunc(con.Invoke(null, new[] { value }));
Run Code Online (Sandbox Code Playgroud)
而且MethodInfo.Invoke还回来了object。关于如何确保参数具有正确类型的任何想法?
小智 5
所有委托均派生自 System.Delegate。您可以使用 System.Delegate.DynamicInvoke 方法来调用编译时不知道其类型的委托,类似于使用 MethodInfo.Invoke() 调用方法。例如:
class Program
{
public static Delegate CreateFunc()
{
return new Func<int, int>(x => x + 1);
}
public static void Main(string[] args)
{
var func = CreateFunc();
object inArg = 42;
object result = func.DynamicInvoke(inArg);
Console.WriteLine(result);
}
}
Run Code Online (Sandbox Code Playgroud)