简体   繁体   English

在C#中使用NumericComparer代码,为什么我的List.Sort()收到转换错误?

[英]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.

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