1

我想为 a 编写一个自定义比较器SortedDictionary,其中键根据它们的类型进行排序。这可能吗?

public class StateBase
{
    // This is a base class I have to inherit from
}

SortedDictionary<StateBase, int> _stateDictionary =
    new SortedDictionary<StateBase, int>(new StateComparer());

class StateComparer : IComparer<StateBase>
{
    public int Compare(StateBase a, StateBase b)
    {
        // I'd like to sort these based on their type
        // I don't particularly care what order they are in, I just want them
        // to be sorted.
    }
}
4

2 回答 2

1

当然,为什么不呢?请注意,我们必须谈论要应用的引用类型,例如:

public class TypeComparer<T> : IComparer<T>, IEqualityComparer<T> where T : class
{
    public static readonly TypeComparer<T> Singleton= new TypeComparer<T>();
    private TypeComparer(){}
    bool IEqualityComparer<T>.Equals(T x, T y)
    {
        if (ReferenceEquals(x, y)) return true;
        if (x == null || y == null) return false;
        Type xType = x.GetType(), yType = y.GetType();
        return xType == yType && EqualityComparer<T>.Default.Equals(x, y);
    }
    int IEqualityComparer<T>.GetHashCode(T x)
    {
        if (x == null) return 0;
        return -17*x.GetType().GetHashCode() + x.GetHashCode();
    }
    int IComparer<T>.Compare(T x, T y)
    {
        if(x==null) return y == null ? 0 : -1;
        if (y == null) return 1;

        Type xType = x.GetType(), yType = y.GetType();
        int delta = xType == yType ? 0 : string.Compare(
               xType.FullName, yType.FullName);
        if (delta == 0) delta = Comparer<T>.Default.Compare(x, y);
        return delta;
    }
}
于 2012-07-05T08:44:47.310 回答
0

你可以。如果您的比较器实现IComparer<T>,它可以通过SortedDictionary相应的构造函数重载传递给一个新实例。

然后该Compare方法以某种方式决定哪个项目更大或更低。这是您可以实现按类型比较逻辑的地方。

Type这是一个根据名称比较实例的示例:

public class TypeComparer : IComparer<Type>
{
    public int Compare(Type x, Type y)
    {
        if(x != null && y != null)
            return x.FullName.CompareTo(y.FullName);
        else if(x != null)
            return x.FullName.CompareTo(null);
        else if(y != null)
            return y.FullName.CompareTo(null);
        else
            return 0;
    }
}
于 2012-07-05T08:39:22.463 回答