使用带有两个参数

时间:2017-05-31 09:29:31

标签: c#

当我使用 Array.sort()尝试两个参数时,我得到其中一个参数的未排序列表。

class Program
{
    static void Main(string[] args)
    {
        Car[] MyAuto = new Car[5];
        MyAuto[0] = new Car("Rusty", 80, 1);
        MyAuto[1] = new Car("Mary", 40, 234);
        MyAuto[2] = new Car("Viper", 40, 34);
        MyAuto[3] = new Car("Mel", 40, 4);
        MyAuto[4] = new Car("Chicky", 40, 5);
        Array.Sort(MyAuto, new PetNameComparer());
        Console.WriteLine("Ordering by pet name:");
        foreach (Car C in MyAuto)
        {
            Console.WriteLine("{0}-{1}", C.CarID, C.PetName);
        }
    }

我通过两个参数得到以下结果:

5-Chicky
234-Mary
4-Mel
1-Rusty
34-Viper

尽管名称按字母顺序排序,但数字不是。而当我只使用一个参数按NUM对列表进行排序时,它会对其进行正确排序:

class Program
{
    static void Main(string[] args)
    {
        Car[] MyAuto = new Car[5];
        MyAuto[0] = new Car("Rusty", 80, 1);
        MyAuto[1] = new Car("Mary", 40, 234);
        MyAuto[2] = new Car("Viper", 40, 34);
        MyAuto[3] = new Car("Mel", 40, 4);
        MyAuto[4] = new Car("Chicky", 40, 5);

        // I just used the Myauto variable which implements Icomparable 
        interface.

        Array.Sort(MyAuto);
        Console.WriteLine("Ordering by CarID);
        foreach (Car C in MyAuto)
        {
            Console.WriteLine("{0}-{1}", C.CarID, C.PetName);
        }
    }

我得到了正确的排序:

1-Rusty
4-Mel
5-Chicky
34-Viper
234-Mary

为什么我无法获得正确的多个ID和名称排序顺序,如下所示,而每个排序顺序分别正常工作?

1-Chicky
4-Mary
5-Mel
34-Rusty
234-Viperv

这是PetNameComparer()`

的实现
class PetNameComparer:IComparer
{
    public int Compare(object x, object y)
    {
        Car t1=x as Car;
        Car t2= y as Car;
        if (t1!=null&t2!=null)          
            return string.Compare(t1.PetName, t2.PetName);
            else          
                throw new ArgumentException("Parameter is not car");          
    }
}

0 个答案:

没有答案