假设我有 6 个方法:Method1()
、Method2()
、Method3()
、Method4( )
、Method5()
和 Method6()
。我还有另一种方法,SuperMethod(int nr)
,它将调用其他方法之一。如果 SuperMethod
的输入为 1,则 Method1()
将被调用,依此类推。
这是否可以在没有 switch 语句或堆叠 if-else 语句的情况下以优雅的方式完成?
我应该补充一点,这不是我正在编写的重要生产代码,因此性能不是问题。
最佳答案
你可以使用委托(delegate),它对于用短程序解决现实世界的问题也很有趣:
public void CollatzTest(int n)
{
var f = new Func<int, int>[] { i => i / 2, i => i * 3 + 1 };
while (n != 1)
n = f[n % 2](n);
}
这也适用于 Action 和直接方法引用
private void DelegateActionStartTest()
{
Action[] Actions = new Action[] { UselesstTest, IntervalTest, Euler13 };
int nFunction = 2;
Actions[nFunction]();
}
关于c# - 按号码调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13917169/