Skip to main content
 首页 » 编程设计

c#之多态性——练习

2024年02月23日14webabcd

好吧,这就是练习:

Define a class named student, containing three grades of students. The class will have a function that calculates the grades average. Now, define a class named student1 which will be derived from student and will add a function to calculate the sum of the grades.In the Main program, define a student variable and object of type student1. Perform placement of the object to variable and run the function of student1.

注意:这不是家庭作业,我是自己学习的。 这是代码:

class Student 
{ 
    protected int grade1, grade2, grade3; 
    public Student(int grade1, int grade2, int grade3) 
    { 
        this.grade1 = grade1; 
        this.grade2 = grade2; 
        this.grade3 = grade3; 
    } 
    public double Average() 
    { 
        return (grade1 + grade2 + grade3) / 3; 
    } 
} 
class Student1 : Student 
{ 
    public Student1(int grade1, int grade2, int grade3) 
        : base(grade1, grade2, grade3) 
    { 
    } 
    public double Sum() 
    { 
        return grade1 + grade2 + grade3; 
    } 
} 
class Program 
{ 
    static void Main(string[] args) 
    { 
    } 
} 

我真的不知道在主课上该做什么,我该如何进行这个布置,而且,我想知道这样做有什么好处,如果到目前为止我有错误,请告诉我,非常感谢。

请您参考如下方法:

好的:我想这就是他们要找的东西,尽管英语有点生硬:

1) 声明学生变量

 Student s; 

2) 声明Student1对象

 Student1 s1 = new Student1(1,2,3); 

3) 执行对象到变量的放置:

s = s1; 

4) 运行该函数(请注意,您必须将 s 转换为 Student1 类型才能访问类型特定的函数 Sum)

Console.WriteLine(((Student1)s).Sum());