各位程序员大家好。 基本上,我想将动态构建的委托(delegate)传递给最小的 api MapGet 或 MapPost 方法。这是构造委托(delegate)的方法:
private static Delegate GetDelegate(Type type, MethodInfo method, ParameterInfo[] parameters)
{
/* Method dynamically build this lambda expression:
* (Type1 arg1, Type2 arg2, ..., TypeN argN) =>
{
var instance = GetTypeInstance(type);
return instance.SomeMethod(arg1, arg2, ..., argN);
}
* Where N = number of arguments
*/
var paramExpresions = new List<ParameterExpression>();
foreach (var parameter in parameters)
paramExpresions.Add(Expression.Parameter(parameter.ParameterType, parameter.Name));
// Instance variable
var instance = Expression.Variable(type, "instance");
// Get instance of type
MethodInfo getTypeInstance = typeof(DynamicControllerCompiler).GetMethod("GetTypeInstance");
var callExpression = Expression.Call(getTypeInstance, Expression.Constant(type));
var expressionConversion = Expression.Convert(callExpression, type);
var assignSentence = Expression.Assign(instance, expressionConversion);
var returnTarget = Expression.Label(method.ReturnType);
var returnExpression = Expression.Return(returnTarget, Expression.Call(instance, method, paramExpresions), method.ReturnType);
var returnLabel = Expression.Label(returnTarget, Expression.Default(method.ReturnType));
var fullBlock = Expression.Block(
new[] { instance },
assignSentence,
returnExpression,
returnLabel
);
var lambda = Expression.Lambda(fullBlock, "testLambda", paramExpresions);
return lambda.Compile();
}
引用的方法“GetTypeInstance”只是从容器返回服务,但为了简单起见,就这样吧:
public static object GetTypeInstance(Type type)
{
return new EchoService();
}
服务非常简单:
public class EchoService
{
public string Echo(string message)
{
return message;
}
public string EchoDouble(string message)
{
return message + "_" + message;
}
}
所以我想将 get 方法映射到最小 api,如下所示:
var type = typeof(EchoService);
foreach (var method in type.GetMethods())
{
ParameterInfo[] parameters = method.GetParameters();
var methodDelegate = GetDelegate(type, method, parameters);
//test
var result = methodDelegate.DynamicInvoke("test");
app.MapGet($"api/{method.Name}", methodDelegate);
}
为了测试动态委托(delegate)是否有效,我用“DynamicInvoke”调用它,一切看起来都很好。然而,如果我将委托(delegate)传递给 MapGet,则会引发错误:
System.InvalidOperationException: 'A parameter does not have a name! Was it generated? All parameters must be named.'
我似乎无法理解发生了什么事。如果由 DynamicInvoke 调用,委托(delegate)可以正常工作,并且所有参数内部都有名称。
最佳答案
问题的根源在于表达式树编译的工作方式。我没有足够的知识来解释原因,但默认情况下它不发出参数名称:
Expression<Func<int, string>> expr = i => i.ToString();
var compiledMethod = expr.Compile().Method;
Console.WriteLine(compiledMethod.GetParameters().Count(p => p.Name != null)); // prints "0"
您可以尝试使用Compile
来克服这个问题重载接受 bool PreferredInterpretation
参数(至少它适用于我的设置),但随后您将面临另一个问题 - 编译方法实际上有两个参数(我认为一个用于处理闭包):
compiledMethod = expr.Compile(true).Method;
Console.WriteLine(compiledMethod.GetParameters().Count(p => p.Name != null)); // prints "2"
我从这里看不到简单的解决方法。
您可以尝试的其他方法 - 使用 System.Reflection.Emit
namespace 动态代码生成或Roslyn但我想说,更好的方法是在构建时使用 source generators 生成此代码.
在某些情况下还有另一种值得考虑的方法 - 创建一个通用方法,其中具有 Map...
所需的设置,并使用反射调用它,就像完成 in this answer 一样。 .
关于c# - 动态委托(delegate)给最小的 api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70563893/