base关键字用于访问派生类中基类的构造函数、字段和方法。我们在 C# 中将此关键字称为“base”。您只能在实例方法、实例属性访问器或构造函数中使用此基本关键字。当基类和派生类都具有相同的字段,并且派生类不会覆盖从基类继承的字段时,base 关键字就变得有用。
语法
C# Base 关键字的语法如下:
base.constructor_name/field_name/method_name;
哪里,
constructor_name 是基类中构造函数的名称,
field_name 是基类中字段的名称,
method_name 是基类中方法的名称。
每当派生类中需要使用基类的构造函数或字段或方法时,我们在派生类中使用关键字base。
在Python中,程序员使用super()函数来引用基类并调用其方法或访问其属性。它提供了一种在派生类中调用基类方法的方法。如果基类和派生类中都存在相同的字段,则 base 关键字很有用;如果派生类没有派生基类中存在的字段,则基关键字没有用处。
通过使用基关键字,可以在派生类中消除必须从基类引用哪个成员的混乱。
以下是提到的示例:
C#程序演示如何使用base关键字在派生类中引用基类的变量:
代码:
using System; //a class called check is defined which is the base class public class check { //a string variable is defined to store the string public string string1 = "Welcome to"; } //another class called check1 is defined which is derived from the base class called check public class check1: check { //another string variable is defined to store the another string string string2 = "C#"; //a method is defined inside the derived class which displays the string from the base class and the derived class as well public void displaymsg() { Console.WriteLine(base.string1); Console.WriteLine(string2); } } //another class called check2 is defined within which the main method is called the instance of the derived class is created and the method of the derived class is called which in turn accesses the variable of the base class public class check2 { public static void Main() { check1 ob = new check1(); ob.displaymsg(); } }
输出:
说明:上面的程序定义了一个名为“Check”的基类,作为父类。它包括一个字符串变量来存储字符串值。在给定的程序中,定义了一个名为“Check1”的派生类,它继承自基类“Check”。在“Check1”派生类中,声明了另一个字符串变量来存储不同的字符串值。此方法显示来自基类和派生类的字符串值。输出如上面的快照所示。
C#程序演示如何使用base关键字在派生类中引用基类的变量:
代码:
using System; //a class called check is defined which is the base class public class check { //a string variable is defined to store the string public string string1 = "Learning is"; } //another class called check1 is defined which is derived from the base class called check public class check1: check { //another string variable is defined to store the another string string string2 = "Fun"; //a method is defined inside the derived class which displays the string from the base class and the derived class as well public void displaymsg() { Console.WriteLine(base.string1); Console.WriteLine(string2); } } //another class called check2 is defined within which the main method is called the instance of the derived class is created and the method of the derived class is called which in turn accesses the variable of the base class public class check2 { public static void Main() { check1 ob = new check1(); ob.displaymsg(); } }
输出:
说明:在给定的程序中,有一个名为“Check”的基类,它充当其他类的父类。它包括一个字符串变量来保存字符串值。此外,定义了一个名为“Check1”的派生类,它继承自基类“Check”。在“Check1”派生类中,声明了一个附加字符串变量来存储不同的字符串值。派生类“Check1”还包含方法定义。此方法显示来自基类和派生类的字符串值。输出如上面的快照所示。
使用base关键字有几个优点;他们是:
1.使用 base 关键字消除了重复代码的需要。
2.通过使用 base 关键字,可以在派生类中消除必须从基类引用哪个成员的混乱。
在本教程中,我们通过编程示例、其输出以及在程序中使用 base 关键字的优点,通过定义、语法和基本关键字的工作原理了解 C# 中基本关键字的概念。
以上是C# 基础的详细内容。更多信息请关注PHP中文网其他相关文章!