【发布时间】:2013-12-26 11:26:46
【问题描述】:
我有一个人的集合,每个人都有一个名字、年龄和国家。名称是字符串,年龄是整数,国家是枚举。我想在这个集合上做一个过滤方法。它的编写方式应该让我以后可以轻松地向过滤器添加新属性,例如电子邮件地址。
GetAllPersonsFilteredBy(string name, int age, Country country)
这种方法的问题是我希望也能够仅按国家/地区过滤而忽略姓名和年龄。
我可以添加以下方法:
GetAllPersonsFilteredByCountry(Country country)
GetAllPersonsFilteredByCountryAndName(Country country, String name)
GetAllPersonsFilteredByCountryAndAge(Country country, int Age)
GetAllPersonsFilteredByName(String Name)
and so on...
但是我会有重复的代码和一堆过滤方法。 另一种选择是检查空值。如果为名称提供 null 或空字符串,则不要过滤名称。问题是您不能将 null 作为枚举的参数!所以我总是必须给出一个国家或国际,即使我只想过滤姓名和年龄而忽略国家。
第三种选择是瀑布式,我首先根据姓名过滤,然后根据年龄过滤,然后根据布尔值过滤国家/地区:
GetAllPersonsFilteredBy(string name, bool filterName, int age, bool filterAge, Country country, bool filterCountry)
{
List<Person> allPersons = getAllPersons();
if (filterName)
//filter all persons out the list based on the name parameter
...
if (filterAge)
//filter all persons out the list based on the age parameter
...
if( filterCountry)
//filter all persons out of the list based on the country parameter
...
return allPersons;
}
这看起来是最好的解决方案,但我不确定。也许我可以在 c# 中使用可选参数和命名参数做一些事情来制作一个健壮但灵活的过滤方法?请考虑枚举不能为空的面孔!
【问题讨论】:
-
1.) 我没有看到枚举 2.) 尝试语言集成查询语法?您可以搜索的 LinQ 和 Lambda 表达式
-
我在第一行说 Country 是一个枚举