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

编辑:谢谢你的答案。 我目前正在努力!!

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

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

// I tried Func 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(); } 

这可能吗?

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

好吧,你可以这样做:

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

然后DoSomething将被声明为Delegate ,这不是非常好。

另一种方法是将方法包装在一个委托中,该委托只执行将返回值作为object所需的任何转换:

 Func method; ... if (choice == "D") // Consider using a switch... { method = BuildMethod(D); } ... // Wrap an existing delegate in another one static Func BuildMethod(Func func) { return () => func(); } 
 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); 
 Func 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(); }