【问题标题】:Compare types of keys for SortedDictionary比较 SortedDictionary 的键类型
【发布时间】:2012-07-05 08:33:32
【问题描述】:

我想为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.
    }
}

【问题讨论】:

  • 所有键都属于同一类型。你能澄清一下吗?

标签: c# types dictionary comparator


【解决方案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;
    }
}

【讨论】:

    【解决方案2】:

    你可以。如果你的比较器实现了IComparer&lt;T&gt;,它可以通过对应的constructor overload传递给一个新的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;
        }
    }
    

    【讨论】:

    • 我想知道是否有一种语言定义的方式来订购Type 对象。排序可以是完全任意的。
    • 老实说,我不知道。但是,它没有实现IComparable。例如,您可以使用他们的名字。我将在帖子中添加一个示例。
    • 啊,对。这个名字是一个完美的解决方案!请将其作为编辑添加到您的答案中,以便我接受。 :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-21
    • 2012-11-16
    • 1970-01-01
    • 2012-09-14
    • 2010-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多