读书人

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

发布时间: 2013-10-08 16:46:23 作者: rapoo

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

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的修饰的方法,会提示

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

读书人网 >C#

热点推荐