通过字符串将方法名称分配给Func

use*_*076 1 c# asp.net c#-4.0

基本上我想这样做:

Func<string> f =  ()=> MyMethodName();
Run Code Online (Sandbox Code Playgroud)

只有一个方法的字符串名称,即:

 Func<string> f =  "MyMethodName";
Run Code Online (Sandbox Code Playgroud)

可以这样做吗?任何问题,警告?反思有帮助吗?我可以先检查方法是否存在吗?

Jon*_*eet 6

你根本不需要lambda表达式.你可以使用Delegate.CreateDelegate:

MethodInfo method = GetType().GetMethod(methodName);
Func<string> func = (Func<string>) Delegate.CreateDelegate(typeof(Func<string>),
                                                           obj, method);
Run Code Online (Sandbox Code Playgroud)

这样就可以避免间接级别,并且您也可以执行一次反射部分而不是每次调用.