接口指定了一组函数成员 , 在类和结构体中实现。
举个例子 , 接口就像是一种能力 , 继承这个接口的类就会获得这个能力,
接口的引用指向已经获得这个能力的类的对象(在方法中会程序会自行判断该类究竟是谁)
编写一个接口实现中国名字和外国名字
声明一个接口
interface IMsg
{
//都是抽象函数 , 默认都是public ,
string getName();
int getAge();
}
定义一个中国名字类继承接口IMsg
class ChinaMsg : IMsg
{
string name;
int age;
public ChinaMsg(string name, int age)
{
this.name = name;
this.age = age;
}
public int getAge()
{
return age;
}
public string getName()
{
return name;
}
}
定义一个外国人类继承接口IMsg
class ForeignerMsg : IMsg
{
string firstName;
string lastName;
int age;
public ForeignerMsg(string firstName, string lastName, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public int getAge()
{
return age;
}
public string getName()
{
return firstName + "·" + lastName;
}
}
定义一个静态方法方便打印
这里面的msg是接口的引用会指向继承该接口的类的对象
static void printPersonMsg(IMsg msg)
{
Console.WriteLine("姓名:" + msg.getName() + "\t年龄:" + msg.getAge());
}
主函数打印看结果
static void Main(string[] args)
{
ChinaMsg xiaoming = new ChinaMsg("小明", 23);
ForeignerMsg Trump = new ForeignerMsg("唐纳德", "特朗普", 24);
printPersonMsg(xiaoming);
printPersonMsg(Trump);
}
————————————————————————————————————————————————
通过接口实现对象之间的比较
Array.sort()方法默认升序
var arrInt = new int[] { 1, 2, 3, 4, 5, 0, 2, 5 };
Array.Sort(arrInt);
for (int i = 0; i < arrInt.Length; i++)
{
if (i == arrInt.Length - 1)
{
Console.WriteLine(arrInt[i]);
}
else
{
Console.Write(arrInt[i] + ",");
}
}
—————————————————————————————————————————————————
IComparable
方法名是CompareTo
对sort()里面public static void Sort<T>(T[] array);
,其中T是泛型数组,会先判断IComparable接口是否实现(程序内部会用 is 判断),不能则会报错。
实现接口里面的CompareTo方法完成对成员属性值的升降排序
class Student : IComparable, IGetSet
{
string name;
int age;
int score;
public string Name { get => name; set => name = value; }
public int Age { get => age; set => age = value; }
public int Score { get => score; set => score = value; }
// 比较两个对象 : 有参考信息作比较
public int CompareTo(object obj)
{
Student otherStudent = (Student)obj;//基类强转成子类对象
if (age > otherStudent.age)
{
return 1;
}
else if (age < otherStudent.age)
{
return -1;
}
else //年龄相等
{
if (score > otherStudent.score)
{
return 1;
}
else if (score < otherStudent.score)
{
return -1;
}
else
{
return 0;
}
}
}
定义一个比较类实现IComparer里面的Compare方法,里面将其他的两个对象的属性值进行比较排序
返回1 、 0 、-1 实现升降序
class ComparerStudent : IComparer
{
public int Compare(object x, object y)
{
//将父类强转成子类对象
Student student1 = (Student)x;
Student student2 = (Student)y;
if (student2.Age > student1 .Age)
{
return 1;
}
else if (student2.Age < student1.Age)
{
return -1;
}
else //年龄相等
{
if (student2.Score > student1.Score)
{
return 1;
}
else if (student2.Score < student1.Score)
{
return -1;
}
else
{
return 0;
}
}
}
}