2015-07-19 74 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

相關問題