阅读背景:

定义Car类,包含两个字段:name和price; (2)在Main方法中,使用Array.Sort方法对Car对象数组根据姓名和价格排序。

来源:互联网 
/*破ide 时好时不好,搞的我以为代码有问题,重建工程后,一切正常, 这是搞毛线,越来越厌恶cjing*/
using System;
using System.Collections;

public class Car
{
    public string name;
    public double price;

    public Car(string name, double price)
    {
        this.name = name;
        this.price = price;
    }

    public override string ToString()
    {
        return string.Format("Car`s name:{0}, price:{1}", name, price);
    }
}

public class PriceComparer : IComparer
{
    public int Compare(Object obj1, Object obj2)
    {
        Car c1 = obj1 as Car;
        Car c2 = obj2 as Car;

        if (c1.price >= c2.price)
            return -1;
        return 1;
    }
}

public class NameComparer : IComparer
{
    public int Compare(Object obj1, Object obj2)
    {
        Car c1 = obj1 as Car;
        Car c2 = obj2 as Car;

        return string.Compare(c1.name, c2.name);
    }
}
public class Example
{
    public static void Main()
    {
        Car[] cars = new Car[4];
        for (int i = 0; i < 4; i++)
        {
            cars[i] = new Car("car" + i, i);
        }

        for (int i = 0; i < 4; i++)
        {
            Console.WriteLine(cars[i].ToString());
        }
        IComparer priceComparer = new PriceComparer();

        
        Array.Sort(cars, priceComparer);

        Console.WriteLine("按价格排序后的:");
        for (int i = 0; i < 4; i++)
        {
            Console.WriteLine(cars[i].ToString());
        }

        IComparer nameComparer = new NameComparer();
        Array.Sort(cars, nameComparer);

        Console.WriteLine("按名字排序后的:");
        for (int i = 0; i < 4; i++)
        {
            Console.WriteLine(cars[i].ToString());
        }
        Console.Read();
    }
}/*破ide 时好时不好,搞的我以为代码有问题,重建工程后,一切正常, 这是搞毛线,越来越厌恶



你的当前访问异常,请进行认证后继续阅读剩余内容。

分享到: