IComparer<T>

作者:追风剑情 发布于:2019-3-15 22:30 分类:C#

示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TSortTest
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Foo> foos = new List<Foo>();
            Random random = new Random();
            for (int i = 0; i < 10; i++)
            {
                Foo foo = new Foo();
                foo.score = random.Next(0, 100);
                foos.Add(foo);
            }

            Console.WriteLine("排序前:");

            foreach (var foo in foos)
            {
                Console.Write(foo.score + " ");
            }

            IComparer<Foo> f = new Foo();
            foos.Sort(f.Compare);

            Console.WriteLine("\n排序后:");

            foreach (var foo in  foos)
            {
                Console.Write(foo.score+" ");
            }

            Console.Read();
        }
    }

    public class Foo : IComparer<Foo>
    {
        public int score;

        public int Compare(Foo a, Foo b)
        {
            if (a.score > b.score)
                return 1;
            else if (a.score < b.score)
                return -1;
            return 0;
        }
    }
}

运行测试

111.png

标签: C#

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号