C# - 接口

Person

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace 接口2
 7 {
 8     // 定义接口 : ICustomCompare
 9     interface ICustomCompare
10     {
11         int CompareTo(object obj);
12     }
13 
14     // 实现接口
15     class Person : ICustomCompare
16     {
17         // 字段
18         private int _age;
19 
20         // 属性
21         public int Age { get; set; }
22 
23         // 方法 : 实现接口 CompareTo
24         public int CompareTo(object obj)
25         {
26             if (null == obj)
27             {
28                 return 1;
29             }
30 
31             Person p = (Person)obj;
32             if (this.Age < p.Age)
33             {
34                 return -1;
35             }
36             else if (this.Age > p.Age)
37             {
38                 return 1;
39             }
40             return 0;
41         }
42     }
43 }

 

Program

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 /*------------------------------------------------------------------------------------------------------------
 7  * 接口 : 
 8  *      1. 关键字 : interface
 9  *      2. 在接口中定义方法不能添加任何访问修饰符, 默认public
10  *      3. 可以定义 : 方法/属性/事件/索引器
11  *      4. 不能定义 : 字段/运算符重载/实例构造函数/析构函数
12  *      5. 所有成员默认public 不能再使用 public/private/proteced
13  *          等访问修饰符,也不能使用static
14 ------------------------------------------------------------------------------------------------------------*/
15 namespace 接口2
16 {
17 
18 
19     class Program
20     {
21         static void Main(string[] args)
22         {
23             Person p1 = new Person();
24             p1.Age = 18;
25             Person p2 = new Person();
26             p2.Age = 19;
27 
28             // 调用接口中的方法,对应p1和p2进行比较
29             if ( p1.CompareTo(p2) > 0 )
30             {
31                 Console.WriteLine("p1 > p2");
32             }
33             else if ( p1.CompareTo(p2) < 0 )
34             {
35                 Console.WriteLine("p1 < p2");
36             }
37             else
38             {
39                 Console.WriteLine("p1 = p2");
40             }
41 
42             Console.ReadLine();
43         }
44     }
45 }

posted @ 2016-04-06 13:58  C/C++/Python/Java  阅读(267)  评论(0编辑  收藏  举报