![](/img/trans.png)
[英]Expression.Lambda: Variable 'x' of type '' referenced from scope '', but it is not defined
[英]Expression.Lambda variable '' of type 'System.String' referenced from scope '', but it is not defined
我正在尝试构建一个将函数委托加载到字典的系统,然后可以从环境中的任何位置调用它们,以向字典要求委托。
我的函数的格式为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);
}
我在Expression.Lambda
行上得到了异常:
范围“”引用了类型为“ System.String”的变量“ param”,但未定义。
PS:
如果在运行时有更好的方法将委托加载到字典中,我将很乐意提供任何建议。
您要调用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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.