我想对类和接口(interface)列表进行排序。所以我的逻辑是
我正在使用 IComparer 界面对列表进行排序。我的模型如下所示:

我的比较器类(如果返回 1 表示 y>x,0 是 x==y -1 是 x>y):
public class SortedTypeComparer : IComparer<Type>
{
/// <summary>
/// Compares types
/// </summary>
public int Compare(Type x, Type y)
{
public int Compare(Type x, Type y)
{
if (y.IsAssignableFrom(x))
{
return 1;
}
else if (x.IsAssignableFrom(y))
{
return -1;
}
else if (!y.IsAssignableFrom(x) && !x.IsAssignableFrom(y) && x.IsInterface && y.IsClass)
{
return 1;
}
else if (!y.IsAssignableFrom(x) && !x.IsAssignableFrom(y) && x.IsClass && y.IsInterface)
{
return -1;
}
else
{
return 0;
}
}
}
}
当我对列表进行排序时,我期望它应该是:
IAnimal
IRunnable
Animal
ICat
Cat
或者:
IRunnable
IAnimal
Animal
ICat
Cat
因为 IRunnable 和 IAnimal 是“相等的”。这是我的用法:
var list = new List<Type>();
list.Add(typeof(IAnimal));
list.Add(typeof(IRunnable));
list.Add(typeof(ICat));
list.Add(typeof(Animal));
list.Add(typeof(Cat));
list.Sort(new SortedTypeComparer());
在这种情况下,它按预期工作。但是,当我更改添加到列表的顺序时(例如将 IRunnable 放在末尾):
var list = new List<Type>();
list.Add(typeof(IAnimal));
list.Add(typeof(ICat));
list.Add(typeof(Animal));
list.Add(typeof(Cat));
list.Add(typeof(IRunnable));
list.Sort(new SortedTypeComparer());
顺序是
IAnimal
Animal
ICat
IRunnable
Cat
这不是我的期望,因为 IRunnable>Animal。似乎当比较 Animal 和 ICat Animal 更高时,当它比较 ICat 和 IRunnable 时,它会说“ICat == IRunnable,所以 Animal 应该 > IRunnable”。如何在 Compare 方法中编写逻辑以按预期对列表进行排序?
最佳答案
我认为 IComparer 不可能做到这一点。来自 CompareTo
- For objects A, B, and C, the following must be true:
- If A.CompareTo(B) returns zero and B.CompareTo(C) returns zero, then A.CompareTo(C) is required to return zero.
因此,如果 A 从 C 继承而 B 不继承任何东西,那么根据您的规则 compareTo 应该返回:
这违反了 CompareTo 的要求。
另一种方法是构建 Directed acyclic graph的层次结构。那么你应该可以使用 Topological sorting对图形进行排序。
关于c# - 类和接口(interface)比较c#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62284699/