I'm using the NumericComparer code located here. 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。排序(新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?
任何想法为什么?
1 个解决方案
#1
5
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
So, if your list is, say a List<decimal>
, you need to supply an IComparer<decimal>
.
所以,如果你的列表是,比如说一个列表 <小数> ,你需要提供一个IComparer
You should be able to quickly put together a class that leverages 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了。排序(新GenericNumericComparer <十进制> ());
(Note you can actually call your generic class NumericComparer
too -- it is distinguished by the type parameter. I added "Generic" here for clarity.)
(注意,您也可以调用泛型类NumericComparer——它是由类型参数区分的。为了清晰起见,我在这里添加了“通用”。
#1
5
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
So, if your list is, say a List<decimal>
, you need to supply an IComparer<decimal>
.
所以,如果你的列表是,比如说一个列表 <小数> ,你需要提供一个IComparer
You should be able to quickly put together a class that leverages 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了。排序(新GenericNumericComparer <十进制> ());
(Note you can actually call your generic class NumericComparer
too -- it is distinguished by the type parameter. I added "Generic" here for clarity.)
(注意,您也可以调用泛型类NumericComparer——它是由类型参数区分的。为了清晰起见,我在这里添加了“通用”。