gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 17:59:57 24 4
gpt4 key购买 nike

我有以下代码:

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>应该可以编译。

关于c# - 如何创建通用类类型的属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2918486/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com