c# - 按号码调用方法

标签 c#

假设我有 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/

相关文章:

c# - 声明静态类,以便它们可以存储在列表中

c# - 从 JSON 字符串中检测 True/False 值

c# - 如何通过C#判断SQL Server数据库用户的有效权限?

c# - 如何访问 .URL 文件中的 URL 和书签标题?

c# - 无法在 C# 应用程序上远程连接到数据库,我可以通过访问该服务器的 phpmyadmin 站点来查看该数据库

c# - 当用接口(interface)模糊类时,重写的实现是否仍然存在?

C#:通过反射访问继承的私有(private)实例成员

C# 和匿名对象数组

c# - LINQ 到实体 : How to return the latest order number for a customer

c# - Nhibernate .Fetch 调用在模拟 session 中失败