Expression.Lambda 从作用域“”引用了 'System.String' 类型的变量“”,但未定义
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
行得到异常:
variable 'param' of type 'System.String' referenced from scope '', but it is not defined.
P.S:
如果有更好的方法在 运行 时间将委托加载到字典,我将很高兴提出任何建议。
您两次调用 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();
我正在尝试构建一个系统,将函数委托加载到字典中,然后可以从环境中的任何地方调用它们,向字典询问委托。
我的函数格式为 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
行得到异常:
variable 'param' of type 'System.String' referenced from scope '', but it is not defined.
P.S:
如果有更好的方法在 运行 时间将委托加载到字典,我将很高兴提出任何建议。
您两次调用 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();