首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较SortedDictionary的密钥类型

比较SortedDictionary的密钥类型
EN

Stack Overflow用户
提问于 2012-07-05 16:33:33
回答 2查看 2.6K关注 0票数 1

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

代码语言:javascript
复制
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.
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-07-05 16:39:22

你可以的。如果您的比较器实现了IComparer,则可以通过相应的constructor overload将其传递给新的SortedDictionary实例。

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

下面是一个基于名称比较Type实例的示例:

代码语言:javascript
复制
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;
    }
}
票数 0
EN

Stack Overflow用户

发布于 2012-07-05 16:44:47

当然,有何不可?请注意,我们必须讨论引用类型才能应用这一点,因此类似于:

代码语言:javascript
复制
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;
    }
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11340613

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档