2014-06-22 22 views
0

我有一個類如何使用類作爲通用

public class Customer 
{ 
    ... 
} 

我也有使用泛型方法:

public static T Show<T>(DependencyObject sender, MessageBoxIcon icon, string caption, ObservableCollection<T> dataSource, MessageBoxButton button) where T : IComparable<T>, new() 
{ 
    ... 
} 

現在,當我想在我的程序調用這個:

Customer customerSelect = NoruBox.Show<Customer>(this, MessageBoxIcon.Box, "GridBox test", customerData, Noru.Controls.MessageBoxButton.SelectCancel); 

我確實得到錯誤壽。它說Customer類型不能用作Show<T>(...)中的類型參數T。沒有從Customer到的隱式參考轉換。


我試圖做public class Customer : IComparable,並添加以下到Class

public int CompareTo(object obj) 
{ 
    var other = obj as Customer; 
    if (other == null) return 0; 
    return CompareTo(other); 
} 

但是這並沒有區別。

+7

您的「客戶」類需要實現「IComparable 」,而不是「IComparable」。 –

+1

你需要這個:http://msdn.microsoft.com/en-us/library/4d7sx9hd(v=vs.110).aspx –

+1

你的'客戶'類有一個無參數的構造函數嗎? – mihai

回答

1

你要比較的方面,每個Customer實例?在下面的例子中,我假設A擁有關鍵值。

public class Customer : IComparable<Customer> 
{ 
    public int CompareTo(Customer other) 
    { 
     if (other == null) return 1; 
     return this.A.CompareTo(other.A); 
    } 
} 
1

的約束要求IComparable<Customer>,不IComparable

public class Customer : IComparable<Customer> { 

    public int CompareTo(Customer other) { 
    ... 
    } 

    ... 
} 
+0

爲什麼downvote?如果你不解釋你認爲什麼是錯的,它不能改善答案。 – Guffa