在C#中,base关键字用于访问基类的字段、构造函数和方法。
只能在实例方法、构造函数或实例属性访问器中使用base关键字。不能在静电方法内部使用。
无涯教程可以使用BASE关键字在派生类中访问基类的字段。如果基类和派生类具有相同的字段,则它很有用。如果派生类没有定义相同的字段,则不需要使用base关键字。派生类可以直接访问基类字段。
看看C#中的base关键字的简单示例,它访问基类的字段。
using System; public class Animal{ public string color = "white"; } public class Dog: Animal { string color = "black"; public void showColor() { Console.WriteLine(base.color); Console.WriteLine(color); } } public class TestBase { public static void Main() { Dog d = new Dog(); d.showColor(); } }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-base.html
来源:LearnFk无涯教程网
white black
借助base关键字,还可以调用基类方法。如果基类和派生类定义相同的方法,则非常有用。换句话说,如果方法被重写。如果派生类没有定义相同的方法,则不需要使用base关键字。基类方法可以由派生类方法直接调用。
让无涯教程来看一个简单的base关键字示例,它调用基类的方法。
using System; public class Animal{ public virtual void eat(){ Console.WriteLine("eating..."); } } public class Dog: Animal { public override void eat() { base.eat(); Console.WriteLine("eating bread..."); } } public class TestBase { public static void Main() { Dog d = new Dog(); d.eat(); } }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-base.html
来源:LearnFk无涯教程网
eating... eating bread...
无论何时继承基类,都会在内部调用基类构造函数。看一下调用基构造函数的示例。
using System; public class Animal{ public Animal(){ Console.WriteLine("animal..."); } } public class Dog: Animal { public Dog() { Console.WriteLine("dog..."); } } public class TestOverriding { public static void Main() { Dog d = new Dog(); } }
输出:
链接:https://www.learnfk.comhttps://www.learnfk.com/csharp/c-sharp-base.html
来源:LearnFk无涯教程网
animal... dog...
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)