2

少し例を挙げてみましょう。

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 に到達するようにする必要があります。実際のデリゲートは、より複雑な署名などを持っている場合があります。

4

2 に答える 2

0
private static class Invoker
{
    private static string Method()
    {
        return "beep";
    }

    public static object Invoke()
    {
        Type type = Type.GetType("Bla.Session, FooSessionDll", true);
        MethodInfo methodInfo = type.GetMethod("Execute");
        Type delegateType = methodInfo.GetParameters()[2].ParameterType;
        Delegate delegateInstance = Delegate.CreateDelegate(delegateType, typeof(Invoker).GetMethod("Method"));
        object[] args = new object[] { "foo", "bar", delegateInstance };
        return methodInfo.Invoke(null, args);
    }
}
于 2010-06-24T03:20:55.043 に答える
0

OK, found the solution: Func<<TResult>>, and the whole family of Func templates. In terms of the example I posted, converting the signature of Execute(...) to:

public static void Execute(string name, string q, Func<string> body) 

is functionally equivalent to the one with explicitly named delegate i.e. any code taking the type dependency on it can still use

Session.Execute("foo", "bar", delegate() { ... });

with zero code change, and any independent dll can now do:

Func<string> d = delegate() { .....} 

and pass it in an Object[] as a normal argument.

There was another thread asking "What’s so great about Func<>" -- well this is :-)

It allows breaking dependencies and unholy tie-ups with zero code change for existing code that uses it. One condition is that existing code used anonymous methods (like in example) and not old-style explicit delegate creation.

于 2010-06-24T22:27:01.487 に答える