小例子大智慧1---C#继承,构造函数

来源:互联网 发布:win10如何开启23端口 编辑:程序博客网 时间:2024/05/01 02:32

1、建立两个实体,学生Student和人Person

     这两个角色都有自己共同的属性,那就是姓名,性别,年龄;而学生有学生成绩

      所以:

     public class Person
    {
        public string Name;

        public string Sex;

        public int Age;

        //构造函数,初始化
        public Person()
        {
            this.Name = "张三";
            this.Sex = "男";
            this.Age = 30;
        }

 

       public string SayHi()
        {
            return "Hell!How are you?";
        }

    }  

而学生直接继承人的实体:

    public class Student : Person
    {

        public int CJ;

        //构造函数,初始化
        public Student()
        {
            this.CJ = 90;
        }

 

       public new string SayHi()//使用new有意隐藏基类方法
        {
            return "你好啊!....";
        }   

     }

然后我在aspx页面放了两个lable

<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label><br />
        <br />
        <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
    </div>
    </form>
</body>

.cs文件中的代码

  protected void Page_Load(object sender, EventArgs e)
    {
        Student s = new Student();
        Label1.Text = "姓名:" + s.Name + ",成绩:" + s.CJ;
        Label2.Text = s.SayHi();
    }

页面显示:

姓名:张三,成绩:90

你好啊!....

有意隐藏了基类中的方法,如果去掉Student中new的修饰的方法,会提示

原创粉丝点击