打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
base 关键字

base 关键字用于从派生类中访问基类的成员:

  • 调用基类上已被其他方法重写的方法。
  • 指定创建派生类实例时应调用的基类构造函数。

基类访问只能在构造函数、实例方法或实例属性访问器中进行。

从静态方法中使用 base 关键字是错误的。

示例

在本例中,基类 Person 和派生类 Employee都有一个名为 Getinfo 的方法。通过使用 base 关键字,可以从派生类中调用基类上的Getinfo 方法。

// keywords_base.cs
// Accessing base class members
using System;
public class Person
{
protected string ssn = "444-55-6666";
protected string name = "John L. Malgraine";

public virtual void GetInfo()
{
Console.WriteLine("Name: {0}", name);
Console.WriteLine("SSN: {0}", ssn);
}
}
class Employee: Person
{
public string id = "ABC567EFG";

public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo();
Console.WriteLine("Employee ID: {0}", id);
}
}

class TestClass {
public static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}

输出

Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG

有关其他示例,请参见 newvirtualoverride

示例

本示例显示如何指定在创建派生类实例时调用的基类构造函数。

// keywords_base2.cs
using System;
public class MyBase
{
int num;

public MyBase()
{
Console.WriteLine("in MyBase()");
}

public MyBase(int i )
{
num = i;
Console.WriteLine("in MyBase(int i)");
}

public int GetNum()
{
return num;
}
}

public class MyDerived: MyBase
{
// This constructor will call MyBase.MyBase()
public MyDerived() : base()
{
}

// This constructor will call MyBase.MyBase(int i)
public MyDerived(int i) : base(i)
{
}

public static void Main()
{
MyDerived md = new MyDerived();
MyDerived md1 = new MyDerived(1);
}
}

输出

in MyBase()
in MyBase(int i)

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
[你必须知道的.NET] 第六回:深入浅出关键字---base和this
C#中 ref 关键字的认识和理解
c#
最简单的C#快速入门教程
C#编程中最常见的10个错误
关于在C#中对类中的隐藏基类方法和重写方法的理解
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服