1.base的用法:用于派生类访问基类成员-->
(1)调用基类上已经被重载的方法(在派生类中重载了该方法)。
(2)指定创建派生类实例时应调用基类的构造方法。
注意:base只能在构造方法、一般方法、实例属性访问器中使用。(不能再静态方法中使用关键字base)
例如:
(1)调用基类上已经被重载的方法
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()
{ 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
例如:
(2)指定创建派生类实例时应调用基类的构造方法。(包括和this的比较)
2.this用法:引用类的当前实例
public class BaseCircle {public BaseCircle(){Console.WriteLine( " no arguments base constructor!!!" );}public BaseCircle( double arg){Console.WriteLine( "double arg base constructor!!!" );}}public class SubCircle : BaseCircle {public SubCircle(): base (){Console.WriteLine( "sub class no argument constructor,actually call base constructor !!!" );}public SubCircle( double a): base (a){Console.WriteLine( "sub class with argument, actually call base double constructor!!!" );}public SubCircle( int k): this (1,2){Console.WriteLine( "sub class with argument int k, actually call sub class constructor int i & j !!!" );}public SubCircle( int i, int j){Console.WriteLine( "sub class with int i&j argument!!!!" );}}static void Main( string [] args){SubCircle s1 = new SubCircle();SubCircle s2 = new SubCircle(1.1);SubCircle s3 = new SubCircle(1);}输出结果为:---->
no arguments base constructor!!!sub class no argument constructor,actually call base constructor !!!double arg base constructor!!!sub class with argument, actually call base double constructor!!!no arguments base constructor!!!sub class with int i&j argument!!!!sub class with argument int k, actually call sub class constructor int i & j !!!注意:
this
只是调用本身,但是这样是需要调用一次基类没有参的构造函数,所以会多显示一条“基类的无参数构造函数. value:0”。
base
是调用基类的有参数构造函数。
其用于引用类的当前实例,也包括继承而来的方法,通常可以隐藏this,MSDN中的小结功能主要包括:
- 限定被相似的名称隐藏的成员
- 将对象作为参数传递到其他方法
- 声明索引器
注意:
由于静态成员函数存在类一级,并不是对象的一部分,因此没有this指针。在静态方法中引用this是错误的。