c# base关键字
1. 调用父类的构造函数
class Father
{
public int Age { get; set; }
public string Name { get; set; }
public Father(int age,string name)
{
this.Age = age;
this.Name = name;
}
}
class Son:Father
{
public int Height { get; set; }
public Son(int age,string name,int height):base (age,name)
{
this.Height = height;
}
}
class grandson : Son
{
public grandson(int age, string name, int height) : base(age, name )
{
this.Height = height;
}
}
会发现上面的代码报错,因为grandson 这个类的构造函数使用base调用父类构造函数时,提示缺少了height这个参数,这是因为base调用的只是它的父类也就是Son这个类的构造函数,而不是最顶层的Father这个类的构造函数,所以这里报错改成如下代码即可:
class Father
{
public int Age { get; set; }
public string Name { get; set; }
public Father(int age,string name)
{
this.Age = age;
this.Name = name;
}
}
class Son:Father
{
public int Height { get; set; }
public Son(int age,string name,int height):base (age,name)
{
this.Height = height;
}
}
class grandson : Son
{
public grandson(int age, string name, int height) : base(age, name,height )
{
this.Height = height;
}
}
2. 调用父类的方法或者属性
class Father
{
public int Age { get; set; }
public string Name { get; set; }
public Father(int age, string name)
{
this.Age = age;
this.Name = name;
}
public void Test()
{
Console.WriteLine("我是Father");
}
}
class Son : Father
{
public int Height { get; set; }
public Son(int age, string name, int height) : base(age, name)
{
this.Height = height;
}
public void Test()
{
Console.WriteLine("我是Son");
}
}
class grandson : Son
{
public grandson(int age, string name, int height) : base(age, name, height)
{
this.Height = height;
}
public void Show()
{
int age = base.Age;
base.Test();
}
}
调用:
grandson father = new grandson(100, "小明", 180);
father.Show();
输出:
我是Son
可以看出调用的方法不是father类中的test方法,而是Son类,也就是grandson的父类的方法。