让我试着举一个小例子。
class Session (
public delegate string CleanBody();
public static void Execute(string name, string q, CleanBody body) ...
可以像这样使用:
Session.Execute("foo", "bar", delegate() { string x="beep"; /* whatever*/ return x; });
但是如果我需要通过 MethodInfo.Invoke 运行——就像在不同的 dll 中一样,两种方式都没有类型依赖关系。像:
Type type = Type.GetType("Bla.Session, FooSessionDll", true);
MethodInfo methodInfo = type.GetMethod("Execute");
Object [] args = { "foo", "bar", delegate() // Doesn't compile, now that ?
{
string x="beep"; /* whatever*/ return x;
}
methodInfo.Invoke("Trial Execution :-)", args);
无论应用什么技巧/演员,它都必须使它仍然作为真正的代表到达 Execute。实际代表可能有更复杂的签名等。