Rel*_*ity 1 c# generics properties
我有这个代码:
public class SelectionList<T> : ObservableCollection<SelectionItem<T>> where T : IComparable<T>
{
// Code
}
public class SelectionItem<T> : INotifyPropertyChanged
{
// Code
}
Run Code Online (Sandbox Code Playgroud)
我需要创建一个类型SelectionList如下的属性:
public SelectionList<string> Sports { get; set; }
Run Code Online (Sandbox Code Playgroud)
但是当我用DataRowView替换字符串时,如
public SelectionList<DataRowView> Sports { get; set; }`
Run Code Online (Sandbox Code Playgroud)
我收到了一个错误.为什么这不起作用?
你的问题是string实现IComparable<string>而DataRowView不是.
SelectionList<T>有一个T必须实现的约束IComparable<T>,因此错误.
public class SelectionList<T> : ObservableCollection<SelectionItem<T>> where T : IComparable<T>
{
// Code
}
Run Code Online (Sandbox Code Playgroud)
一种解决方案是将DataRowView子类化并实现IComparable:
public class MyDataRowView : DataRowView, IComparable<DataRowView>{
int CompareTo(DataRowView other) {
//quick and dirty comparison, assume that GetHashCode is properly implemented
return this.GetHashCode() - (other ? other.GetHashCode() : 0);
}
}
Run Code Online (Sandbox Code Playgroud)
那SelectionList<MyDataRowView>应该编译好.