我不会为此使用直接枚举。我会创建一堆IComparer<T>
可供选择的实现:
public static class SortingStrategy
{
public static readonly IComparer<Person> ByAgeDescending = ...;
public static readonly IComparer<Person> ByAgeAscending = ...;
public static readonly IComparer<Person> ByIncomeDescending = ...;
public static readonly IComparer<Person> ByIncomeAscending = ...;
}
...或者很可能使用组合来执行升序/降序部分(例如,通过扩展方法IComparer<T>
创建一个反向包装器)。
当然,现在这不会强制调用者使用您的预定义值之一。您可以通过使用自己的类来强制它:
public abstract class SortingStrategy : IComparer<Person>
{
public static readonly SortingStrategy ByAgeDescending = ...;
public static readonly SortingStrategy ByAgeAscending = ...;
public static readonly SortingStrategy ByIncomeDescending = ...;
public static readonly SortingStrategy ByIncomeAscending = ...;
private SortingStrategy() {}
private class ByAgeStrategy : SortingStrategy { ... }
private class ByIncomeStrategy : SortingStrategy { ... }
}
这里私有构造函数阻止任何其他子类,但私有嵌套类仍然可以对其进行子类化,因为它们可以访问构造函数。
然后,您可以使您的方法采用 aSortingStrategy
而不仅仅是IComparer<T>
.
当然,正如 James 所建议的,从长远来看,使用 LINQ 可能会更加灵活。这取决于你的目标是什么。