我的基础测试里有这道题,我是这样做的:
/// <summary>
/// 同一个类实例化的对象具有相同的字段,属性及方法,而校长不收作业这里理解为不调用该方法。
/// </summary>
/// <param name="args"></param>
static void Main(string[] args)
{
//实例化一个老师的person类。
person teacher = new person();
teacher.Name = "张老师";
teacher.Age = -24;
teacher.Sex='三';
teacher.CollectWork();
//实例化一个学生的pers类。
person student = new person();
student.Name = "李同学";
student.Age = 200;
student.Sex='女';
student.CollectWork();
//实例化一个校长的person类。
person Headmaster = new person();
Headmaster.Name = "王校长";
Headmaster.Age=37;
Headmaster.Sex='男';
Console.ReadKey();
}
public class person
{
public string wds = "";
string name;
char sex;
int age;
public int Age
{
get { return age; }
set { age = (value>=0&&value<150)?value:0; }
}
public char Sex
{
get { return sex; }
set { sex = (value=='男'||value=='女')?value:'男'; }
}
public string Name
{
get { return name; }
set { name = value; }
}
public void CollectWork()
{
Console.WriteLine("{0}要来收作业啦!",name);
Console.WriteLine();
}
abstract class Person
{
public abstract void homework();
}
class Student:Person
{
public override void homework()
{
Console.WriteLine("我是学生,我会收作业");
}
}
class Teacher : Person
{
public override void homework()
{
Console.WriteLine("我是老师,我会收作业");
}
}
class Headmaster : Person
{
public override void homework()
{
Console.WriteLine("我是校长,我才不会收作业");
}
}
class Program
{
static void Main(string[] args)
{
Student stu = new Student();
stu.homework();
Teacher tea = new Teacher();
tea.homework();
Headmaster master = new Headmaster();
master.homework();