C# base关键字用法解释(怎么理解)

2022-08-01 教育 67阅读
1.用于从派生类中访问基类的成员:调用基类上已被其他方法重写的方法。

前半句实例:
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
{
static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
后半句反例:
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);
}
public virtual void GetInfo1()
{
Console.WriteLine("Name: {0}-1", name);
Console.WriteLine("SSN: {0}-1", ssn);
}
}
class Employee : Person
{
public string id = "ABC567EFG";

public override void GetInfo()
{
// Calling the base class GetInfo method:
base.GetInfo1(); //GetInfo1并没有被重写
Console.WriteLine("Employee ID: {0}", id);
}
}

class Program
{
static void Main(string[] args)
{
Employee E = new Employee();
E.GetInfo();

}
}

2.指定创建派生类实例时应调用的基类构造函数。

public class BaseClass
{
int num;

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

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

public int GetNum()
{
return num;
}
}

public class DerivedClass : BaseClass
{
// This constructor will call BaseClass.BaseClass()
public DerivedClass()
: base()
{
}

// This constructor will call BaseClass.BaseClass(int i)
public DerivedClass(int i)
: base(i)
{
}

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

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

记住不要在静态方法中使用base即可。语法上也通不过。It is an error to use the base keyword from within a static method.
声明:你问我答网所有作品(图文、音视频)均由用户自行上传分享,仅供网友学习交流。若您的权利被侵害,请联系fangmu6661024@163.com