C#入门之类(补充)

前面我们有讲过 C# 中的类,今天我们补充点,关于类的继承的内容。

在实际的环境中,我们的对象都是不相同的,但也会有很多相同的地方。如,在学校里面,有学生,也有老师,但学生和老师都有姓名和年龄等属性,同时学生也有一些独特的属性,如班级信息,选择的课程信息等等。

此时,我们就可以通过类继承的方式来定义,我们将定义一个基(础)类 people,它将包含姓名(name)和年龄(age),同时,基于该基类创建一个派生类,包含学生的班级信息和课程信息。使用同样的方式创建一个类文件,并在类文件中定义类:

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApp31
{
    class people      // 基类(父类)
    {
        public string name;
        public int age;
    }
    class students : people   //派生类(子类),将继承基类的属性信息
    {
        public string Class;
        public string course;
        
        public string say()
        {
            return "He is " + name + ", and he is " + age + " years old. He is a " + Class + " student, and he is taking a " + course + " class.";
        }
    }
}

现在,我们可以在主文件中,直接调用该 students 类,同时,该 students 类也包含了 people 类的属性:

using System;

namespace ConsoleApp31
{
    class Program
    {
        static void Main(string[] args)
        {
            students s = new students();
            s.name = "Tom";
            s.age = 23;
            s.Class = "third year in university";
            s.course = "computer";
            Console.WriteLine(s.say());
        }
    }
}

运行结果:

He is Tom, and he is 23 years old. He is a third year in university student, and he is taking a computer class.

<<:  Day 16:108. Convert Sorted Array to Binary Search Tree

>>:  Day 0x14 - 订单查询 (Part2 : View)

Day 16 - Apply

到目前为止我们已经知道了 Functor 可以将 effect 跟 pure function 进行...

Day 28. F2E-过渡动画

系列文接近尾声,专案最後要来做一个过渡动画效果 我们要做的效果是向左/右滑入滑出,效果可以参考 V...

Day 13 ( 中级 ) 大型数字 ( 图形数字 )

大型数字 ( 图形数字 ) 教学原文参考:大型数字 ( 图形数字 ) 如果要在 Scratch 3 ...

Day 30-单元测试(结尾)

今年很荣幸有机会参加 iT 铁人赛,其一方面是要强迫自己对单元测试有更多一点的认识;另一方面是想透过...

用React刻自己的投资Dashboard Day2 - 网站Wireframe设计

tags: 2021铁人赛 React 投资Dashboard内容设计 要实际动手制作wirefra...