我想对类和接口(interface)列表进行排序。所以我的逻辑是
- 如果类没有实现接口(interface),则比接口(interface)高,否则比接口(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 应该返回:
- A.CompareTo(B) -> 0
- B.CompareTo(C) -> 0
- A.CompareTo(C) -> 1
这违反了 CompareTo 的要求。
另一种方法是构建一个 Directed acyclic graph的层次结构。那么你应该可以使用Topological sorting对图表进行排序。
关于c# - 类和接口(interface)比较 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62284699/