2015-07-19 73 views
0

我想建立一个系统,加载功能代表字典,然后他们可以从任何地方调用环境要求字典中的代表。Expression.Lambda变量''的类型'System.String'引用范围'',但它没有被定义

我的函数是一个格式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',但它不是定义。

P.S:
如果有更好的方式来代表加载在运行时的字典,我会很乐意的任何建议。

回答

3

你打给Expression.Parameter两次,这会给你不同的表达式。不要那样做 - 只需调用一次,并使用​​这两个地方你需要它:

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(); 
+0

谢谢,作品像一个魅力。 – Amorphis

相关问题