从范围“”引用了“System.String”类型的 Expression.Lambda 变量“”,但未定义

Amo*_*his 1 c# reflection

我正在尝试构建一个系统,将函数委托加载到字典中,然后可以从环境中的任何地方调用它们,向字典询问委托。

我的函数是一种格式Func<string, string>

我的代码是

var methods = typeof(Keywords)
    .GetMethods()
    .Where(mt => mt.GetCustomAttributes(typeof(KDTAttribute), false).Count() > 0);

foreach (var method in methods)
{
    string key = ((KDTAttribute)method.GetCustomAttributes(typeof(KDTAttribute), false)[0]).Keyword;
    var combinedArgumentsExp = new Expression[] { Expression.Parameter(typeof(string),"param") };
    var mtCall = Expression.Call(Expression.Constant(me), method,combinedArgumentsExp);
    ParameterExpression targetExpr = Expression.Parameter(typeof(string), "param");
    Func<string, string> result = Expression.Lambda<Func<string, string>>(mtCall, targetExpr).Compile();
    retVal.Add(key, result);
}
Run Code Online (Sandbox Code Playgroud)

我收到异常消息Expression.Lambda

从范围“”引用了“System.String”类型的变量“param”,但未定义。

PS:
如果有更好的方法在运行时将委托加载到字典中,我将很乐意提供任何建议。

Jon*_*eet 5

你打了Expression.Parameter两次电话,这给了你不同的表达方式。不要这样做 - 只需调用一次,然后在ParameterExpression您需要的两个地方使用它:

var parameter = Expression.Parameter(typeof(string),"param");
string key = ((KDTAttribute)method.GetCustomAttributes(typeof(KDTAttribute), false)[0]).Keyword;
var mtCall = Expression.Call(Expression.Constant(me), method, parameter);
var result = Expression.Lambda<Func<string, string>>(mtCall, parameter).Compile();
Run Code Online (Sandbox Code Playgroud)