1)定义Student类,用string型变量name存储学生姓名,用int型变量age存储学生年龄。Student类实现IComparable接口。要求从键盘输入学生的姓名和年龄,并注意可能出现的异常及其处理。IComparable接口定义如下(系统已定义,可直接使用)
interface IComparable
{
int CompareTo(object obj);
//如果自身与obj相等返回0,<obj返回-1,>obj返回1 ,注意可能出现的异常
}
(2)定义Student类的派生类Master。
(3)定义Sort类,定义静态方法BubbleSortDescending(IComparable[] bubbles),实现对象的降序排列。其中,在该方法中调用接口方法CompareTo(object obj)比较两个对象的“大小”。
(4)定义Test类,按给定数据生成Student实例数组,调用BubbleSortDescending(IComparable[] bubbles)使之按姓名排序,按给定数据生成Master实例数组,调用BubbleSortDescending(IComparable[] bubbles)使之按年龄排序,请遍历输出排序前后数组中每个元素实例中的name和age。如果Master实例a与Student实例b比较,总是a>b
(5)实验数据
Name |
Age |
Tom |
|
Nick |
|
Mike |
(a)当这三个学生全为Student的实例时,输出排序后的结果;
(b)当这三个学生全为Master类的实例时,输出排序后的结果
(c)(选作)任意指定数组中元素的类型(Student或Master),输出排序后的结果
(6)分析并解释实验结果。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace Q4
{
interface IComparable
{
int CompareTo(object obj);
} class Student : IComparable
{
string name;
int age;
public Student(string name, int age)
{
this.name = name;
this.age = age; } public virtual int CompareTo(object obj)//对接口的方法进行重写
{
Student other = (Student)obj;
if (other != null)
{
if (string.Compare(name,other.Name)<0) return 1;
else if (string.Compare(name, other.name) == 0) return 0;
else return -1;
}
else
throw new ArgumentException("Object is not a Student");
}
public string Name
{
get
{
return name;
}
} public int Age
{
get
{
return age;
}
}
} class Master : Student
{
string name;
int age;
public Master(string name, int age) : base(name, age)
{
this.name = name;
this.age = age;
}
public override int CompareTo(object obj)//override 对student里的compareto方法进行重写
{
Master other = (Master)obj;//强制类型转换
if (other!= null)//判断是否空,异常
{
if (age < other.Age) return 1;
else if (age == other.Age) return 0;
else return -1;
}
else
throw new ArgumentException("Object is not a Master");
} public new string Name
{
get
{
return name;
}
} public new int Age
{
get
{
return age;
}
}
} class Sort
{
static IComparable g;//在静态函数里面的变量也要用静态
public static void BubbleSortDescending(IComparable[] bubbles)
//因为这里student类继承icomparable,而master继承student,所以这里要用ICmparable
{
for (int i = 0; i < bubbles.Length - 1; i++)
{
if (bubbles[i].CompareTo(bubbles[i + 1]) > 0)
{
g = bubbles[i];
bubbles[i] = bubbles[i + 1];
bubbles[i + 1] = g; }
}
}
} class Test
{
static void Main(string[] args)
{
IComparable[] a = new Student[3];//用了多态,因为Student继承IComparable,所以可以这样写
a[0] = new Student("Tom", 18);//c初始化,也是要用new
a[1] = new Student("Nike", 20);
a[2] = new Student("Mike", 17);
Sort.BubbleSortDescending(a);
foreach(Student b in a )//a是数组名所以直接 in a
{
Console.WriteLine("{0}----{1}", b.Name, b.Age);
} Master[] c = new Master[3];
c[0] = new Master("Tom", 18);
c[1] = new Master("Nike ", 20);
c[2] = new Master("Mike", 17);
Sort.BubbleSortDescending(c);
Console.WriteLine();
foreach(Master d in c)
{
Console.WriteLine("{0}----{1}", d.Name, d.Age);
} }
}
}