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

2020-04-02 08:37发布

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...

3条回答
Anthone
2楼-- · 2020-04-02 08:46
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();
}
查看更多
Animai°情兽
3楼-- · 2020-04-02 08:47

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();
}
查看更多
Fickle 薄情
4楼-- · 2020-04-02 08:58
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); 
查看更多
登录 后发表回答