标题: 调用父类构造函数给子类字段赋值 [打印本页] 作者: 孔健 时间: 2013-3-11 23:46 标题: 调用父类构造函数给子类字段赋值 在类的继承中,子类不会继承父类构造函数,但是会默认调用父类无参的构造函数;
如果要显示的调用父类的有参数构造函数,要用base关键字。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace base调用基类构造方法
{
class Program
{
static void Main(string[] args)
{
Teacher teacher = new Teacher("tom",25,"20130311");
Console.ReadKey();
}
}
class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Person(string name ,int age)
{
this.Name = name;
this.Age = age;
}
}
class Teacher : Person
{
public string Id { get; set; }
public Teacher(string name ,int age,string id)
:base(name,age)
{
this.Id = id;
Console.WriteLine("大家好,我叫{0},今年{1}了,我的编号是{2}.", this.Name, this.Age, this.Id);
}
}
}