简体   繁体   English

如何创建通用类类型的属性?

[英]How to create a property of generic class type?

I have this code: 我有以下代码:

public class SelectionList<T> : ObservableCollection<SelectionItem<T>> where T : IComparable<T>
{
  // Code 
}

public class SelectionItem<T> : INotifyPropertyChanged
{
// Code
}

I need to create a property which is of the type SelectionList as follows: 我需要创建一个类型为SelectionList的属性,如下所示:

public SelectionList<string> Sports { get; set; }

But when I replace string with DataRowView, as 但是当我用DataRowView替换字符串时,

 public SelectionList<DataRowView> Sports { get; set; }`

I am getting an error. 我收到一个错误。 Why doesn't this work? 为什么不起作用?

Your problem is that string implements IComparable<string> and DataRowView doesn't. 您的问题是string实现了IComparable<string>DataRowView没有实现。

SelectionList<T> has a constraint that T must implement IComparable<T> , hence the error. SelectionList<T>有一个约束,即T必须实现IComparable<T> ,因此是错误的。

public class SelectionList<T> : ObservableCollection<SelectionItem<T>> where T : IComparable<T>
{
  // Code 
}

One solution would be to subclass DataRowView and implement IComparable : 一种解决方案是子类化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);
  }
}

Then SelectionList<MyDataRowView> should compile fine. 然后SelectionList<MyDataRowView>应该可以正常编译。

You have a constraint on your class where T : IComparable<T> . 您在类上有一个约束where T : IComparable<T> DataRowView does not implement IComparable<DataRowView> and therefore cannot be used in this case. DataRowView不实现IComparable<DataRowView> ,因此在这种情况下不能使用。

See here for more information about Generic Constraints: http://msdn.microsoft.com/en-us/library/d5x73970.aspx 有关通用约束的更多信息,请参见此处: http : //msdn.microsoft.com/zh-cn/library/d5x73970.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM