我有一个函数,我可以在其中发送项目所有类型的所有对象,它应该遍历属性并输出它们的值:
public void ShowMeAll(IEnumerable<object> items);
IEnumerable<Car> _cars = repository.GetAllCars();
ShowMeAll(_cars);
IEnumerable<House> _houses = repository.GetAllHouses();
ShowMeAll(_houses);
好的,举个例子,是这样的。现在,我想将一个属性发送到我的 ShowMeAll 函数中,我想通过它对我的项目进行排序,然后输出。使用函数参数执行此操作的最正确方法是什么?
最佳答案
最简单的方法是让 LINQ 为您完成,通过 the OrderBy() method .例如:
IEnumerable<Car> _cars = repository.GetAllCars();
ShowMeAll(_cars.OrderBy(car => car.Make));
IEnumerable<House> _houses = repository.GetAllHouses();
ShowMeAll(_houses.OrderBy(house => house.SquareFootage));
这样,您就删除了 ShowMeAll
的要求了解传入对象的属性。因为你传递了List<object>
,我认为这是需要的。 :)
关于c# - 我如何将我的类的属性发送到函数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8569665/