有没有办法在变量中保存方法,然后再调用它?如果我的方法返回不同类型怎么办?

Yuf*_*Yuf 10 c# methods delegates

编辑:谢谢你的回答.我目前正在研究它!!

我有3个方法,S()返回字符串,D()返回double,B()返回bool.

我还有一个变量来决定我使用哪种方法.我想这样做:

    // 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();
    }
Run Code Online (Sandbox Code Playgroud)

这可能吗?

我读过这篇文章: 将一个方法存储为C#中一个类的成员变量 但是我需要存储具有不同返回类型的方法...

Jon*_*eet 17

好吧,你可以这样做:

Delegate method;

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

然后DoSomething将被宣布为正义Delegate,这不是非常好.

另一种方法是将方法包装在一个委托中,该委托只执行获取返回值所需的任何转换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();
}
Run Code Online (Sandbox Code Playgroud)

  • @Eric:我承认这不是不包括约束开始的原因......但事后听起来不错:) (2认同)