C# base this的使用

来源:互联网 发布:mysql教材推荐 编辑:程序博客网 时间:2024/06/05 01:53
 

base

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

调用基类上已被其他方法重写的方法。

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

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

示例:

在派生类中调用基类方法。

// base 关键字

// 访问基类成员

using System;

public class BaseClass

{

protected string _className = "BaseClass";

public virtual void PrintName()

{

Console.WriteLine("Class Name: {0}", _className);

}

}

class DerivedClass : BaseClass

{

public string _className = "DerivedClass";

public override void PrintName()

{

Console.Write("The BaseClass Name is {0}");

//调用基类方法

base.PrintName();

Console.WriteLine("This DerivedClass is {0}", _className);

}

}

class TestApp

{

public static void Main()

{

DerivedClass dc = new DerivedClass();

dc.PrintName();

}

}

/**//*

控制台输出:

The BaseClass Name is BaseClass

This DerivedClass is DerivedClass

*/

在派生类中调用基类构造函数。先访问基类的构造函数,然后再访问本类的构造函数

// keywords_base2.cs

using System;

public class BaseClass

{

intnum;

public BaseClass()

{

Console.WriteLine("in BaseClass()");

}

public BaseClass(int i)

{

num = i;

Console.WriteLine("in BaseClass(int {0})", num);

}

}

public class DerivedClass : BaseClass

{

// 该构造器调用 BaseClass.BaseClass()

public DerivedClass() : base()

{

}

// 该构造器调用 BaseClass.BaseClass(int i)

public DerivedClass(int i) : base(i)

{

}

static void Main()

{

DerivedClass dc = new DerivedClass();

DerivedClass dc1 = new DerivedClass(1);

}

}

/**//*

控制台输出:

in BaseClass()

in BaseClass(1)

*/

注意点

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

base 主要用于面向对象开发的对态这方面,在示例2中有体现。

this

this 关键字引用类的当前实例。

以下是 this 的常用用途:

限定被相似的名称隐藏的成员

将对象作为参数传递到其他方法

声明索引器

示例:

综合示例。

// this 关键字

// keywords_this.cs

using System;

class Employee

{

private string _name;

private int _age;

private string[] _arr = new string[5];

public Employee(string name, int age)

{

// 使用this限定字段,name与age

this._name = name;

this._age = age;

}

public string Name

{

get { return this._name; }

}

public int Age

{

get { return this._age; }

}

// 打印雇员资料

public void PrintEmployee()

{

// 将Employee对象作为参数传递到DoPrint方法

Print.DoPrint(this);

}

// 声明索引器

public string this[intparam]

{

get { return _arr[param]; }

set { _arr[param] = value; }

}

}

class Print

{

public static void DoPrint(Employee e)

{

Console.WriteLine("Name: {0}\nAge: {1}", e.Name, e.Age);

}

}

class TestApp

{

static void Main()

{

Employee E = new Employee("Hunts", 21);

E[0] = "Scott";

E[1] = "Leigh";

E[4] = "Kiwis";

E.PrintEmployee();

for(int i=0; i<5; i++)

{

Console.WriteLine("Friends Name: {0}", E[i]);

}

Console.ReadLine();

}

}

/**//*

控制台输出:

Name: Hunts

Age: 21

Friends Name: Scott

Friends Name: Leigh

Friends Name:

Friends Name:

Friends Name: Kiwis

*/

注意点

由于静态成员函数存在于类一级,并且不是对象的一部分,因此没有 this 指针。在静态方法中引用 this 是错误的。

索引器允许类或结构的实例按照与数组相同的方式进行索引。索引器类似于属性,不同之处在于它们的访问器采用参数。