base其实最大的使用地方在面相对象开发的多态性上,base可以完成创建派生类实例时调用其基类构造函数或者调用基类上已被其他方法重写的方法。
例如:
2.1关于base调用基类构造函数
-
-
-
-
-
Console.WriteLine("Build A");
-
-
-
-
-
-
-
Console.WriteLine("Build B");
-
-
-
-
-
-
-
创建一个B的实例对象,获得结果是同时打印Build A和Build B.
2.2关于base在派生类中调用基类的方法。
-
-
-
public virtual void Hello()
-
-
Console.WiriteLine("Hello");
-
-
-
-
-
public override void Hello()
-
-
-
Console.WiriteLine("World");
-
-
这样如果程序调用B.Hello()获得的效果将会使Hello World.
最后补充下,根据MSDN Library介绍来看这两个关键字都是属于[访问关键字]类型
+++++++++++++++++++++++++++++ 无敌分割线 +++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++ 文章二 +++++++++++++++++++++++++++++
关于base
base 关键字用于从派生类中访问基类的成员:
调用基类上已被其他方法重写的方法。
指定创建派生类实例时应调用的基类构造函数。
基类访问只能在构造函数、实例方法或实例属性访问器中进行。
示例:
1. 在派生类中调用基类方法。
-
-
-
-
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}");
-
-
-
Console.WriteLine("This DerivedClass is {0}", _className);
-
-
-
-
-
public static void Main()
-
-
DerivedClass dc = new DerivedClass();
-
-
-
2. 在派生类中调用基类构造函数。
-
-
-
-
-
-
-
-
Console.WriteLine("in BaseClass()");
-
-
-
-
-
Console.WriteLine("in BaseClass(int {0})", num);
-
-
-
public class DerivedClass : BaseClass
-
-
-
-
-
-
-
-
public DerivedClass(int i)
-
-
-
-
-
-
DerivedClass dc = new DerivedClass();
-
DerivedClass dc1 = new DerivedClass(1)();
-
-
-
注意:
从静态方法中使用 base 关键字是错误的。
base 主要用于面向对象开发的对态这方面,在示例2中有体现。
关于this
this 关键字引用类的当前实例。
以下是 this 的常用用途:
限定被相似的名称隐藏的成员
将对象作为参数传递到其他方法
声明索引器
示例:
-
-
-
-
-
-
-
-
private string[] _arr = new string[5];
-
public Employee(string name, int age)
-
-
-
-
-
-
-
-
get { return this._name; }
-
-
-
-
get { return this._age; }
-
-
-
public void PrintEmployee()
-
-
-
-
-
-
public string this[int param]
-
-
get { return _arr[param]; }
-
set { _arr[param] = value; }
-
-
-
-
-
public static void DoPrint(Employee e)
-
-
Console.WriteLine("Name: {0}\nAge: {1}", e.Name, e.Age);
-
-
-
-
-
-
-
Employee E = new Employee("Hunts", 21);
-
-
-
-
-
for (int i = 0; i < 5; i++)
-
-
Console.WriteLine("Friends Name: {0}", E[i]);
-
-
-
-
转:https://www.cnblogs.com/eedc/p/6343201.html
C#中base关键字的几种用法:base()
原文:https://www.cnblogs.com/841019rossi/p/14829537.html