base 关键字用于从派生类中访问基类的成员:
1,调用基类上已被其他方法重写的方法。
2,指定创建派生类实例时应调用的基类构造函数。
3,基类访问只能在构造函数、实例方法或实例属性访问器中进行。
4,还有从静态方法中使用 base 关键字是错误的
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
{
static void Main()
{
Employee E = new Employee();
E.GetInfo();
}
}
结果:
Name: John L. Malgraine
SSN: 444-55-6666
Employee ID: ABC567EFG
说白了!就是先执行基类的方法在执行派生类的方法!
//实现基类的构照函数
public Order() : base(queuePath, queueTimeout) {
// Set the queue to use Binary formatter for smaller foot print and performance
queue.Formatter = new BinaryMessageFormatter();
}
base关键字用于从派生类中访问基类成员时使用!即使基类的方法已经在派生类中重写,仍可以使用base关键字调用。而且,在创建派生类的实例时,可以使用base关键字调用基类的构造函数,使用base关键字只能访问基类的构造函数,实例方法和实例属性,不能访问基类的静态方法。