2016-09-27 54 views
3

我如何能實現IComparerC#IComparable的IComparer的額外帕拉姆

int CompareTo(object obj)

有附加參數,如

int CompareTo(object obj, Dictionary<int, int> preferences)

喜好是Id字典和NumberOfClicks<int, int>

我想要的是比較e字典中的點擊次數爲categoryId的內容,

示例Cat 1有3次點擊,Cat 2有6次點擊。

排序比較 preferences[this.CategoryId].value > preferences[object.CategoryId].value

所以他們按類別排序,但相對於Dictionary

+0

您顯示的簽名來自「IComparable」,而不是「IComparer」。 – dasblinkenlight

回答

5

您不能將額外參數傳遞給IComparerCompare方法,因爲方法簽名必須與接口中的簽名匹配。

你可以做什麼是構造IComparer實例,其額外的參數,它存儲在實例,使用內部CompareTo需要:

class MyComparer : IComparer<object> { 
    private readonly IDictionary<int, int> preferences; 
    public MyComparer(IDictionary<int, int> preferences) { 
     this.preferences = preferences; 
    } 
    public int Compare(object a, object b) { 
     ... // Perform the comparison with preferences in scope 
    } 
} 
0

創建實現IComparer<T>一個獨立的比較器類,而而不是讓類型本身實現IComparable,並讓它在構造函數中接受Dictionary。比較器可以在比較對象的實例時使用字典。