我正在尝试构建一个系统,将函数委托加载到字典中,然后可以从环境中的任何地方调用它们,向字典询问委托。
我的函数是一种格式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:
如果有更好的方法在运行时将委托加载到字典中,我将很乐意提供任何建议。