我假设你有三个类实现了IRule(AddRule,EditRule,DeleteRule)。
如果你可以将allRules的类型从IList改为List,你可以使用
List<T>.Sort(Comparison<T>)
方法。
Comparison是一个带有以下签名的通用委托
public delegate int Comparison<in T>(T x,T y)
所以你需要像这样的东西:
public int IRuleComparer(IRule first, IRule second)
{
//build a table of type weights (this could be made static)
Dictionary<Type, int> typeWeights = new Dictionary<Type, int>();
typeWeights.Add(typeof(AddRule), 1);
typeWeights.Add(typeof(EditRule), 2);
typeWeights.Add(typeof(DeleteRule), 3);
//get the types of the arguments
Type firstType = first.GetType();
Type secondType = second.GetType();
//are the types valid?
if (!typeWeights.ContainsKey(firstType))
throw new Exception("invalid first type");
if (!typeWeights.ContainsKey(secondType))
throw new Exception("invalid second type");
//compare the weights of the types
return typeWeights[firstType].CompareTo(typeWeights[secondType]);
}
另外,请注意排序实现使用的是快速排序算法,这不是一种稳定的排序算法,也就是说它可能会打乱 AddRules 的相对顺序,所以在你的例子中,AddRule2 可能会在 AddRule1 之前被排序。
或者,您可以使用LINQ并编写类似以下内容的代码:
public int GetRuleWeight(IRule item)
{
//build a table of type weights (this could be made static)
Dictionary<Type, int> typeWeights = new Dictionary<Type, int>();
typeWeights.Add(typeof(AddRule), 1);
typeWeights.Add(typeof(EditRule), 2);
typeWeights.Add(typeof(DeleteRule), 3);
Type itemType = item.GetType();
if (!typeWeights.ContainsKey(itemType))
throw new Exception("invalid type");
return typeWeights[itemType];
}
allRules = allRules.OrderBy(item => GetRuleWeight(item)).ToList();
这将适用于 IList(甚至包括 IEnumerable),因此您不必更改 allRules 的类型。
A1 A2 E1 D1 D2 D3
这样的结果,还是像A2 A1 E1 D2 D3 D1
这样的顺序也可以呢? - AakashMList<T>
有一个Sort
方法。而IList<T>
没有(因此问题不同)。你在示例中使用了List
,但在标题中使用了IList
。 - xanatos