我怎样才能重构这个switch语句?

And*_*sky 1 lambda switch-statement

昨天我在玩jQGrid插件和ASP.NET.一切都很好,我的网格现在正在工作,但我有两种方法,让我的代码闻起来.

臭方法:

private IOrderedEnumerable<Employee> GetOrderedEmployees(Column sortColumn, bool ascending)
    {
        switch (sortColumn)
        {
            case Column.Name:
                {
                    return GetOrderedEmployees(e => e.Name, ascending);
                }
            case Column.Salary:
                {
                    return GetOrderedEmployees(e => e.Salary, ascending);
                }
            default:
                {
                    return GetOrderedEmployees(e => e.ID, ascending);
                }
        }
    }

    private IOrderedEnumerable<Employee> GetOrderedEmployees<TSortKey>(Func<Employee, TSortKey> func, bool ascending)
    {
        return ascending ? Context.Employees.OrderBy(func) : Context.Employees.OrderByDescending(func);
    }
Run Code Online (Sandbox Code Playgroud)

我无法找到,如何正确地重构它们.似乎最好的解决方案是return e=>e.Name在switch语句中只返回lambdas(fe ),但是怎么做呢?

在switch语句中,ascending参数传递了3次.这不是重复吗?

Ed *_* S. 7

我想你可能会在这里超越顶峰.返回lambdas(IMO)比简单的switch语句或if; else if; else block更令人困惑.可能有更好的方法,但有时你需要检查一个条件,特别是列(我讨厌使用ListViews,但它们是必要的,并且经常需要这种代码.)

我不认为你处于需要重构任何东西的地步.如果那个switch语句成为一个维护头痛的问题,那么就不要过去了,但并不是所有的switch语句都构成了"代码味道".

要解决代码重复问题,可以使用开关来获取e.?? 首先,保存该值,然后在方法结束时调用该函数一次.