2012-07-05 28 views
1

我想寫一個SortedDictionary的自定義比較器,其中鍵根據其類型進行排序。這可能嗎?比較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. 
    } 
} 
+0

這些鍵將全部爲相同類型。你能澄清一下嗎? – Jon

回答

0

你可以。如果您的比較器實現了IComparer<T>,則可以通過相應的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; 
    } 
} 
+0

我想知道是否有定義'Type'對象的語言定義方式。排序可以是完全任意的。 –

+0

我不知道,說實話。但是,它不實現'IComparable'。例如,你可以使用他們的名字。我會在帖子中添加一個示例。 –

+0

啊,對。該名稱是一個完美的解決方案!請將它作爲編輯添加到您的答案,以便我可以接受它。 :) –

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; 
    } 
}