【发布时间】:2011-07-07 06:24:56
【问题描述】:
有没有办法为基类类型实现专门的 IComparer,以便子类仍然可以使用它在特定集合中进行排序?
例子
public class A
{
public int X;
}
public class B:A
{
public int Y;
}
public AComparer:IComparer<A>
{
int Compare(A p1, A p2)
{
//...
}
}
所以下面的代码可以工作:
List<A> aList = new List<A>();
aList.Sort(new AComparer());
List<B> bList = new List<B>();
bList.Sort(new AComparer()); // <- this line fails due to type cast issues
如何解决这个问题以同时具有排序和专用集合的继承(并且不为每个子类复制 IComparer 类?
提前致谢!
【问题讨论】:
标签: collections .net-2.0 c#-2.0