c# 参考之访问关键字:base、this_c#应用

2008-02-23 05:41:50来源:互联网 阅读 ()

新老客户大回馈,云服务器低至5折

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
{
int num;

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[int param]
{
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 是错误的。
索引器允许类或结构的实例按照和数组相同的方式进行索引。索引器类似于属性,不同之处在于他们的访问器采用参数。


标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇: c#中dispose和close的区别_c#应用

下一篇: c#中四种进程或线程同步互斥的控制方法_c#应用