C#自定义类实现IComparable实现List排序c#基础学习

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 using System.Collections;
 8 
 9 namespace day01
10 {
11     
12     class Class20
13     {
14         static void Main(string[] args)
15         {
16             ArrayList list = new ArrayList();
17 
18             list.Add(new Person("zhangsan", 103));
19             list.Add(new Person("lisi", 54));
20             list.Add(new Person("wangwu", 25));
21 
22             list.Sort();
23             foreach(Person temp in list)
24             {
25                 Console.WriteLine(temp.ToString());
26             }
27 
28  
29 
30             Console.ReadKey();
31         }
32     }
33     public class Person : IComparable
34     {
35         public string Name;
36         public int Age;
37         public Person()
38         {
39 
40         }
41         public Person(string name,int age)
42         {
43             Name = name;
44             Age = age;
45         }
46         public override string ToString()
47         {
48             return "name: " + Name + " age: " + Age;
49         }
50         public int CompareTo(object obj)
51         {
52             if(obj is Person)
53             {
54                 Person person = obj as Person;
55                 {
56                     return this.Age - person.Age;
57                 }
58             }
59             else
60             {
61                 throw new ArgumentException("对象转化异常");
62             }
63         }
64     }
65  
66     
67 }

 

posted @ 2019-04-07 22:01  littlelittleprince  阅读(570)  评论(0编辑  收藏  举报