Is there a way to save a method in a variable then

2020-04-02 08:13发布

问题:

Edit: Thank you for the answers. I am currently working on it!!\

I have 3 methods, S() returns string, D() returns double and B() returns bool.

I also have a variable that decides which method I use. I want do this:

    // I tried Func<object> method; but it says D() and B() don't return object.
    // Is there a way to use Delegate method; ? That gives me an eror saying method group is not type System.Delegate
    var method;

    var choice = "D";

    if(choice=="D")
    {
        method = D;
    }
    else if(choice=="B")
    {
        method = B;
    }
    else if(choice=="S")
    {
        method = S;
    }
    else return;

    DoSomething(method); // call another method using the method as a delegate.

    // or instead of calling another method, I want to do:
    for(int i = 0; i < 20; i++){
       SomeArray[i] = method();
    }

Is this possible?

I read this post: Storing a Method as a Member Variable of a Class in C# But I need to store methods with different return types...

回答1:

Well, you could do:

Delegate method;

...
if (choice == "D") // Consider using a switch...
{
    method = (Func<double>) D;
}

Then DoSomething would be declared as just Delegate, which isn't terribly nice.

Another alternative would be to wrap the method in a delegate which just performs whatever conversion is required to get the return value as object:

Func<object> method;


...
if (choice == "D") // Consider using a switch...
{
    method = BuildMethod(D);
}

...

// Wrap an existing delegate in another one
static Func<object> BuildMethod<T>(Func<T> func)
{
    return () => func();
}


回答2:

private delegate int MyDelegate();
private MyDelegate method;


    var choice = "D";

    if(choice=="D")
    {
        method = D;
    }
    else if(choice=="B")
    {
        method = B;
    }
    else if(choice=="S")
    {
        method = S;
    }
    else return;

    DoSomething(method); 


回答3:

Func<object> method;

var choice = "D";

if(choice=="D")
{
    method = () => (object)D;
}
else if(choice=="B")
{
    method = () => (object)B;
}
else if(choice=="S")
{
    method = () => (object)S;
}
else return;

DoSomething(method); // call another method using the method as a delegate.

// or instead of calling another method, I want to do:
for(int i = 0; i < 20; i++){
   SomeArray[i] = method();
}