c# base关键字的具体使用
作者:GeGe&YoYo
base关键字用于从派生类中访问基类的成员,本文主要介绍了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的父类的方法。
到此这篇关于c# base关键字的具体使用的文章就介绍到这了,更多相关c# base关键字内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
