我需要帮助使这个方法通用。重复大约十次以获得不同 Web 列表控件的列表(用“MyType”代替特定控件中使用的类型)。
private static IList<MyType> GetList(RequestForm form)
{
// get base list
IMyTypeRepository myTypeRepository = new MyTypeRepository(new HybridSessionBuilder());
IList<MyType> myTypes = myTypeRepository.GetAll();
// create results list
IList<MyType> result = new List<MyType>();
// iterate for active + used list items
foreach (MyType myType in myTypes)
{
if (myType.Active || form.SolutionType.Contains(myType.Value))
{
result.Add(myType);
}
}
// return sorted results
result.OrderBy(o => o.DisplayOrder);
return result;
}
如果这还不够,请告诉我。我认为这需要我刚刚熟悉的更高级的语言功能。也许我应该让它们都使用同一个存储库?
感谢您的帮助。
编辑: 感谢您的帮助。我没有任何同行的支持,所以这个董事会很棒,我从你们每个人那里学到了一些东西。我希望我能接受所有的答案。
最佳答案
你可以先像这样让你的函数更简洁一点:
private static IList<MyType> GetList(RequestForm form)
{
// get base list
IMyTypeRepository myTypeRepository =
new MyTypeRepository(new HybridSessionBuilder());
IList<MyType> myTypes = myTypeRepository.GetAll();
return myTypes.Where(x => x.Active || form.SolutionType.Contains(x.Value))
.OrderBy(x => x.DisplayOrder).ToList();
}
此时,该函数的大部分内容都与MyType
直接相关,因此如何进一步改进它很大程度上取决于MyType
与其他函数的关系涉及的类型。例如,这是一个假设版本,如果您的其他类型遵循(对我来说)看起来合理的契约(Contract),您可以编写:
private static IList<T> GetList(RequestForm form) where T : OrderedValueContainer
{
// we'll want to somehow genericize the idea of a TypeRepository that can
// produce these types; if that can't be done, we're probably better off
// passing a repository into this function rather than creating it here
var repository = new TypeRepository<T>(new HybridSessionBuilder());
IList<T> myTypes = repository.GetAll();
// the hypothetical OrderedValueContainer class/interface
// contains definitions for Active, Value, and DisplayOrder
return myTypes.Where(x => x.Active || form.SolutionType.Contains(x.Value))
.OrderBy(x => x.DisplayOrder).ToList();
}
关于c# - 干这个方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/920742/