深入解析C#编程中的事件(2)

上一篇 / 下一篇  2008-04-22 21:11:20 / 个人分类:技术文章

实例变量初始化函数
当一个构造函数没有构造初始化函数或一个形式为base(...)的构造函数初始化函数, 构造函数就就隐含的执行被类中声明的实例域的变量初始化函数指定的初始化。这与赋值序列相关,这些赋值在直接基类构造函数的隐式调用前,在构造函数的入口 被直接执行。变量初始化函数按照它们在类声明中出现的文字顺序执行。
构造函数执行
可以把一个实例变量初始化函数和一个构造函数初始化函数,看作是自动插在构造函数主体中的第一条语句前。例子
using System.Collections;
class A
{
 int x = 1, y = -1, count;
 public A() {
count = 0;
 }
 public A(int n) {
count = n;
 }
}
class B: A
{
 double sqrt2 = Math.Sqrt(2.0);
 ArrayList items = new ArrayList(100);
 int max;
 public B(): this(100) {
items.Add("default");
 }
 public B(int n): base(n - 1) {
max = n;
 }
}

包含了许多变量初始化函数,并且也包含了每个形式(base和this)的构造函数初始化函数。这个例子与下面介绍的例子相关,在那里,每条注释指明了一个自动插入的语句(自动插入构造函数调用所使用的语法不是有效的,至少用来演示这个机制)。

using System.Collections;
class A
{
 int x, y, count;
 public A() {
x = 1; // Variable initializer
y = -1; // Variable initializer
object(); // Invoke object() constructor
count = 0;
 }
 public A(int n) {
x = 1; // Variable initializer
y = -1; // Variable initializer
object(); // Invoke object() constructor
count = n;
 }
}
class B: A
{
 double sqrt2;
 ArrayList items;
 int max;
 public B(): this(100) {
B(100); // Invoke B(int) constructor
items.Add("default");
 }
 public B(int n): base(n - 1) {
sqrt2 = Math.Sqrt(2.0); // Variable initializer
items = new ArrayList(100); // Variable initializer
A(n - 1); // Invoke A(int) constructor
max = n;
 }
}

注意变量初始化函数被转换为赋值语句,并且那个赋值语句在对基类构造函数调用前执行。这个顺序确保了所有实例域在任何访问实例的语句执行前,被它们的变量初始化函数初始化。例如:

class A
{
 public A() {
PrintFields();
 }
 public virtual void PrintFields() {}
}
class B: A
{
 int x = 1;
 int y;
 public B() {
y = -1;
 }
 public override void PrintFields() {
Console.WriteLine("x = {0}, y = {1}", x, y);
 }
}

当new B() 被用来创建B的实例时,产生下面的输出:
x = 1, y = 0

因为变量初始化函数在基类构造函数被调用前执行,所以x的数值是1。可是,y的数值是0(int的默认数值),这是因为对y的赋值直到基类构造函数返回才被执行。
默认构造函数
如果一个类不包含任何构造函数声明,就会自动提供一个默认的构造函数。默认的构造函数通常是下面的形式

public C(): base() {}


这里C是类的名称。默认构造函数完全调用直接基类的无参数构造函数。如果直接基类中没有可访问的无参数构造函数,就会发生错误。在例子中

class Message
{
 object sender;
 string text;
}


因为类不包含构造函数声明,所以提供了一个默认构造函数。因此,这个例子正好等同于

class Message
{
 object sender;
 string text;
 public Message(): base() {}
}

TAG:

 

评分:0

我来说两句

显示全部

:loveliness: :handshake :victory: :funk: :time: :kiss: :call: :hug: :lol :'( :Q :L ;P :$ :P :o :@ :D :( :)

日历

« 2008-07-09  
  12345
6789101112
13141516171819
20212223242526
2728293031  

数据统计

  • 访问量: 55897
  • 日志数: 24223
  • 建立时间: 2007-12-06
  • 更新时间: 2008-06-15

RSS订阅

Open Toolbar