[英]How to create a property of generic class type?
我有以下代码:
public class SelectionList<T> : ObservableCollection<SelectionItem<T>> where T : IComparable<T>
{
// Code
}
public class SelectionItem<T> : INotifyPropertyChanged
{
// Code
}
我需要创建一个类型为SelectionList
的属性,如下所示:
public SelectionList<string> Sports { get; set; }
但是当我用DataRowView替换字符串时,
public SelectionList<DataRowView> Sports { get; set; }`
我收到一个错误。 为什么不起作用?
您的问题是string
实现了IComparable<string>
而DataRowView
没有实现。
SelectionList<T>
有一个约束,即T
必须实现IComparable<T>
,因此是错误的。
public class SelectionList<T> : ObservableCollection<SelectionItem<T>> where T : IComparable<T>
{
// Code
}
一种解决方案是子类化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);
}
}
然后SelectionList<MyDataRowView>
应该可以正常编译。
您在类上有一个约束where T : IComparable<T>
。 DataRowView不实现IComparable<DataRowView>
,因此在这种情况下不能使用。
有关通用约束的更多信息,请参见此处: http : //msdn.microsoft.com/zh-cn/library/d5x73970.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.