1

I have a method that I call multiple times, but each time a different method with a different signature is called from inside.

public void MethodOne()
{
//some stuff

*MethodCall();

//some stuff

}

So MethodOne is called multiple times, each time with a different *MethodCall(). What I'm trying to do is something like this :

public void MethodOne(Func<> MethodCall)
{
//some stuff

*MethodCall;

//some stuff

}

but the Methods that are called each have a different return type and different parameters. Is there a way to do this using Functors? If not, how would I go about doing this?

Thank you!

4

4 回答 4

1

You best bet would be to use the non-generic Action type (or MethodInvoker would be the same), i.e.

public void MethodOne(Action callback)
{
    //some stuff

    if(callback != null) callback();

    //some stuff
}

From this you can call any method by wrapping it at the caller, i.e.

MethodOne(SimpleMethod); // SimpleMethod has no parameters and returns void
MethodOne(() => MoreComplexMethod(1, "abc")); // this one returns void
MethodOne(() => { MethodThatReturnsSomething(12); }); // anything you like

etc

于 2012-10-30T10:55:53.860 回答
1

You cannot call a function which requires parameters without supplying them, so the answer is "no, not possible"

Also, maybe you want the following:

void MethodOne(Action a)
{
    // some stuff
    a();
    // some stuff
}

... // somewhere in the code
MethodOne((Action)(() => { DoSomethingOther(1, 2, 3); }));
MethodOne((Action)(() => { DoSomethingEvenDifferent(1, 2, 3, 4, 5); }));
于 2012-10-30T10:58:34.657 回答
1

Every delegate in .Net is an instance of a class derived from Delegate. So if you really wish to pass 'any' delegate to a method, you can pass it as Delegate

To invoke it, you need to use its DynamicInvoke method.

public void MethodOne(Delegate MethodCall)
{
//some stuff

//Assuming you now have the required parameters
//or add params object[] args to the signature of this method
object res = MethodCall.DynamicInvoke(args); //args is object[] representing the parameters

//some stuff
}

But this is not recommended as DynamicInvoke is slow and it does not offer any compile time safety. Probably you should revisit your design.

于 2012-10-30T11:09:21.270 回答
0

This is basically not possible. You could make MethodOne generic for the return type, and use a lambda that closes over its outside block instead of parameters:

static void Main(string[] args)
{
    int parameterSubst = 1;
    int result = MethodOne<int>(() => parameterSubst);
    string result2 = MethodOne<string>(() =>
    {
        string s = parameterSubst.ToString();
        s += "foo";
        return s;
    });
}

static T MethodOne<T>(Func<T> function)
{
    return function();
}

As you can see, parameterSubst is used in the passed Func<T>s, but not as a parameter.

于 2012-10-30T10:59:26.653 回答