c# - Refactor dublicate methods with generics -


i have methods. how can refactor code have generic method?

first method:

    void changeprojectname(datamodel datamodel)     {          foreach (project project in datamodel.projects)         {             string projectname = project.name;             projectname = changename(projectname);              project.name = projectname;         }          datamodel.submitchanges();     } 

second method:

    void changeemployeename(datamodel datamodel)     {         foreach (employee employee in datamodel.employees)         {             string employeename = employee.name;             employeename = changename(employeename);              employee.name = employeename;         }          datamodel.submitchanges();     } 

we must able t type collection appropriate property in model, must pass selection strategy it:

void changename<t>(datamodel datamodel,                    func<datamodel, ienumerable<t>> selector)     t : ihavename {      foreach (t x in selector(datamodel))     {         x.name = changename(x.name);     }      datamodel.submitchanges(); } 

and usage:

changename(model, x => x.projects); 

you can add action<t> parameter , pass x => x.name = changename(x.name) if want avoid having ihavename interface (or base class, etc).


Comments

Popular posts from this blog

Fail to load namespace Spring Security http://www.springframework.org/security/tags -

sql - MySQL query optimization using coalesce -

unity3d - Unity local avoidance in user created world -