对象是数据(字段)和行为(方法)的封装体,要想执行对象的行为则需要调用对象拥有的方法。楼主应分别调用学生和teacher的SayHello()方法。- class Program
- {
- static void Main(string[] args)
- {
- Student stu = new Student {Name = "小明", Age = 16, Habit = "喜欢弹钢琴"};
- stu.SayHello();
- Teacher teacher = new Teacher {Name = "李明", Age = 27, Exp = 5};
- teacher.SayHello();
- Console.ReadKey();
- }
- }
- class Student
- {
- public string Name;
- public int Age;
- public string Habit;
- public void SayHello()
- {
- Console.WriteLine("大家好,我叫{0},我今年{1}岁,我的爱好是{2}", Name, Age, Habit);
- }
- }
- class Teacher
- {
- public string Name;
- public int Age;
- public int Exp;
- public void SayHello()
- {
- Console.WriteLine("大家好,我叫{0},我今年{1}岁,我工作了{2}年了", Name, Age, Exp);
- }
- }
复制代码 |