我无法找出如何为泛型类实现 IComparable
接口方法 CompareTo
。
我有一个名为 BindingProperty
的类,用于创建 List>
来绑定到 DataGrid
。问题是我无法执行排序操作,因为此 BindingProperty
类未实现 IComparable
接口。比较的结果取决于 BindingProperty
类的数据成员“Value”,其中“Value”的类型为 T。当我单击 DataGrid 的列标题时,我收到一个异常,即 CompareTo()
方法未实现。
我需要帮助来实现这个接口。我应该使用 IComparable
吗?如果是,我该怎么做?
提前致谢
沙克蒂
I am not able to find out as to how to implement the IComparable
interface method CompareTo
for a generic class.
I have a class called BindingProperty<T>
which is used to create a List<BindingProperty<intOrString>>
to bind to a DataGrid
. The problem is that the I can not perform the Sort operation as the IComparable
interface is not implemented by this BindingProperty<T>
class. The result of comparison would depend on a data member 'Value' of the the BindingProperty<T>
class where 'Value' is of Type T. When I click on the column header of the DataGrid, I get an exception that CompareTo()
method is not implemented.
I would need help to implement this interface. Should I be using IComparable<T>
? If yes, how do I do it?
Thanks in advance
Shakti
发布评论
评论(3)
在 T 上设置通用类型约束。
编辑:
如果 value 未实现 IComparable ,则处理替代解决方案。这将支持所有类型,只是如果它们没有实现
IComparable
,则不会排序。Set up a generic type constraint on T.
Edit:
Alternative solution to handle if value does not implement
IComparable
. This will support all types, just wont sort if they do not implementIComparable
.如果 Type 是自定义类,那么您的自定义类需要是 IComparable。
例如
List
,则FooClass
需要继承/实现IComparable
。If the Type is a custom class, then your custom class needs to be IComparable.
e.g.
List<FooClass>
, thenFooClass
needs to inherit/implementIComparable
.您可以使用通用约束来要求
T
实现IComparable
。然后,您可以通过比较两个BindingProperty
实例的Value
成员来比较它们。我不清楚您是否需要您的类实现IComparable
或IComparable
但实现两者并不需要太多额外的工作。You can use a generic constraint to require that
T
implementsIComparable<T>
. You can then compare twoBindingProperty<T>
instance by comparing theirValue
members. It is not clear to me if you need your class to implementIComparable
orIComparable<T>
but implemeting both is not much extra work.