不同属性的通用foreach循环

时间:2014-01-08 20:59:28

标签: c# generics foreach generic-collections generic-method

我正在尝试使用foreach循环的泛型方法,它将传递不同的参数作为参数。

在下面的这个例子中,我想传递不同的参数(EmployeeDisplayOrder或EmployeeEnrollOrder)

public void SaveEmployeeDisplayOrder(ICollection<Employee> employees)
{
   //some code

   foreach( var emp in employees)
   {
      UpdateSpecificEmployeeOrder(employee.id, e => e.EmployeeDisplayOrder);
   }
}

public void SaveEmployeeEnrollOrder(ICollection<Employee> employees)
{
   //some code

   foreach( var emp in employees)
   {
     UpdateSpecificEmployeeOrder(employee.id, e => e.EmployeeEnrollOrder);
   }
}

我想有类似的东西

public void UpdateEmployeeOrders(ICollection<Employee> employee)
{ 
  foreach( var emp in employees)
  {
    UpdateSpecificEmployeeOrder(employee.id, //generic property);
  }
}

并从SaveEmployeeDisplayOrder和SaveEmployeeEnrollOrder调用此UpdateEmployeeOrders泛型方法。

UpdateSpecificEmployeeOrder的方法签名

UpdateSpecificEmployeeOrder( int employeeid, params Expression<Func<Employee, object>>[] property)

这可能吗?

2 个答案:

答案 0 :(得分:10)

让方法接受一个表达式,就像你传递它的方法一样:

public class Foo
{
    public void UpdateEmployeeOrders(IEnumerable<Employee> employees,
         Expression<Func<Employee, object>> selector)
    {
        foreach (var employee in employees)
        {
            UpdateSpecificEmployeeOrder(employee.id, selector);
        }
    }
}

此外,由于我们对employees执行的唯一操作是对其进行迭代,因此我们可以将参数键入IEnumerable而不是ICollection。它提供了此方法所需的所有保证,同时允许更广泛的可能输入类型。

答案 1 :(得分:1)

你的回答中有答案......你正在使用lambdas ...所以在你的方法中传递一个委托。

public void SaveEmployeeDisplayOrder<T>(ICollection<Employee> employees, Func<Employee, T> fetchProperty)
{
   //some code

   foreach( var employee in employees)
   {
      UpdateSpecificEmployeeOrder(employee.id, fetchProperty(employee));
   }
}

然后你会把它称之为你所拥有的:

SaveEmployeeDisplayOrder(employees, e => e.EmployeeDisplayOrder);

SaveEmployeeDisplayOrder(employees, e => e.EmployeeEnrollOrder);