public class Student
{
private string _Name;
private int _Age;
private int _Sex;
/// <summary>
/// 构造函数
/// </summary>
public Student():this("",0,0)
{
}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="name"></param>
public Student(string name):this(name,10,1)
{}
/// <summary>
/// 构造函数
/// </summary>
/// <param name="name"></param>
/// <param name="age"></param>
public Student(string name, int age):this(name, age, 2)
{ }
/// <summary>
/// 构造函数
/// </summary>
/// <param name="name"></param>
/// <param name="age"></param>
/// <param name="sex"></param>
public Student(string name, int age, int sex)
{
_Name = name;
_Age = age;
_Sex = sex;
}
/// <summary>
/// 姓名
/// </summary>
public string Name
{
get { return _Name; }
set { _Name = value; }
}
/// <summary>
/// 年龄
/// </summary>
public int Age
{
get { return _Age; }
set { _Age = value; }
}
/// <summary>
/// 性别
/// </summary>
public int Sex
{
get { return _Sex; }
set { _Sex = value; }
}
}调用示例:
Student student1 = new Student();
Response.Write(string.Format("Name:{0},Age:{1},Sex:{2}<br/>",student1.Name,student1.Age,student1.Sex));
Student student2 = new Student("dnawo");
Response.Write(string.Format("Name:{0},Age:{1},Sex:{2}<br/>", student2.Name, student2.Age, student2.Sex));
Student student3 = new Student("dnawo", 20);
Response.Write(string.Format("Name:{0},Age:{1},Sex:{2}<br/>", student3.Name, student3.Age, student3.Sex));结果:
Name:,Age:0,Sex:0
Name:dnawo,Age:10,Sex:1
Name:dnawo,Age:20,Sex:2
如上边例子所示,重载构造函数的调用必须借助this关键字来进行,而不能像普通函数那样调用,否则将出错。
评论(0)
暂无评论。