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.