[英]Using NumericComparer code in C#, why I am getting a conversion error for my List.Sort()?
I'm using the NumericComparer code located here. 我正在使用此处的NumericComparer代码。 It's very easy to add it to a project: NumericComparer
将其添加到项目中非常容易: NumericComparer
I have a List of strings with numbers in them and my code is simply this: myList.Sort(new NumericComparer());
我有一个包含数字的字符串列表,我的代码就是这样:
myList.Sort(new NumericComparer());
The error I am getting is this: 我得到的错误是这样的:
cannot convert from 'ns.NumericComparer' to 'System.Collections.Generic.IComparer' 无法从“ ns.NumericComparer”转换为“ System.Collections.Generic.IComparer”
Any ideas why? 有什么想法吗?
It looks like the Sort
method is expecting an implementation of IComparer<T>
-- generic, with a type parameter, whereas NumericComparer
implements the non-generic IComparer
interface. 看起来
Sort
方法期望使用类型参数实现IComparer<T>
泛型实现,而NumericComparer
实现非泛型的IComparer
接口。
So, if your list is, say a List<decimal>
, you need to supply an IComparer<decimal>
. 因此,如果您的列表为
List<decimal>
,则需要提供IComparer<decimal>
。
You should be able to quickly put together a class that leverages NumericComparer
: 您应该能够快速组合利用
NumericComparer
的类:
public class GenericNumericComparer<T> : IComparer<T>
{
private static readonly NumericComparer _innerComparer = new NumericComparer();
public int Compare(T x, T y)
{
return _innerComparer.Compare(x, y); // I'm guessing this is how NumericComparer works
}
}
So now you can call myList.Sort(new GenericNumericComparer<decimal>());
因此,现在您可以调用
myList.Sort(new GenericNumericComparer<decimal>());
(Note you can actually call your generic class NumericComparer
too -- it is distinguished by the type parameter. I added "Generic" here for clarity.) (请注意,您实际上也可以调用通用类
NumericComparer
-它由type参数区分。为清楚起见,在此添加了“ Generic”。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.