c# – 不同属性的通用foreach循环
作者:互联网
我试图使用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)
这可能吗?
解决方法:
你的答案中有答案……你正在使用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);
标签:c,foreach,generics,generic-collections,generic-method 来源: https://codeday.me/bug/20190716/1477856.html