使用泛型重构方法

时间:2015-07-22 16:55:41

标签: c# generics refactoring

我有一些方法。我如何重构此代码以获得通用方法?

第一种方法:

    void ChangeProjectName(DataModel dataModel)
    { 
        foreach (Project project in dataModel.Projects)
        {
            string projectName = project.Name;
            projectName = ChangeName(projectName);

            project.Name = projectName;
        }

        dataModel.SubmitChanges();
    }

第二种方法:

    void ChangeEmployeeName(DataModel dataModel)
    {
        foreach (Employee employee in dataModel.Employees)
        {
            string employeeName = employee.Name;
            employeeName = ChangeName(employeeName);

            employee.Name = employeeName;
        }

        dataModel.SubmitChanges();
    }

2 个答案:

答案 0 :(得分:4)

我们必须能够从模型中的相应属性中获取T类型集合,因此我们必须为其传递选择策略:

void ChangeName<T>(DataModel dataModel,
                   Func<DataModel, IEnumerable<T>> selector)
    where T : IHaveName
{ 
    foreach (T x in selector(dataModel))
    {
        x.Name = ChangeName(x.Name);
    }

    dataModel.SubmitChanges();
}

和用法:

ChangeName(model, x => x.Projects);

如果您想避免使用Action<T>接口(或基类等),可以添加x => x.Name = ChangeName(x.Name)参数并将其传递给IHaveName

答案 1 :(得分:1)

我认为,如果单独更改提交数据的名称,则会更好。

void ChangeName<T>(IEnumerable<T> list) where T : IHaveName
{ 
    foreach (T item in list)
    {
        item.Name = ChangeName(project.Name);
    }
}

void ChangeNamesAndSubmitChanges(dataModel dataModel)
{ 
    ChangeName(dataModel.Projects);
    ChangeName(dataModel.Employees);
    dataModel.SubmitChanges();
}

或根据Yorye Nathan的建议创建带有委托的ChangeNamesAndSubmitChanges。