详解C#编程中构造函数的使用

2019-12-26 17:30:52于海丽

只要创建基于 CoOrds 类的对象,就会调用此实例构造函数。诸如此类不带参数的构造函数称为“默认构造函数”。然而,提供其他构造函数通常十分有用。例如,可以向 CoOrds 类添加构造函数,以便可以为数据成员指定初始值:


// A constructor with two arguments:
public CoOrds(int x, int y)
{
  this.x = x;
  this.y = y;
}

这样便可以用默认或特定的初始值创建 CoOrd 对象,如下所示:


CoOrds p1 = new CoOrds();
CoOrds p2 = new CoOrds(5, 3);

如果某个类没有构造函数,则会自动生成一个默认构造函数,并使用默认值来初始化对象字段。例如,int 初始化为 0。有关默认值的更多信息,请参见 默认值表(C# 参考)。因此,由于 CoOrds 类的默认构造函数将所有数据成员都初始化为零,因此可以将它完全移除,而不会更改类的工作方式。本主题的稍后部分的示例 1 中提供了使用多个构造函数的完整示例,示例 2 中提供了自动生成的构造函数的示例。
也可以用实例构造函数来调用基类的实例构造函数。类构造函数可通过初始值设定项来调用基类的构造函数,如下所示:


class Circle : Shape
{
  public Circle(double radius)
    : base(radius, 0)
  {
  }
}

在此示例中,Circle 类将表示半径和高度的值传递给 Shape(Circle 从它派生而来)提供的构造函数。使用 Shape 和 Circle 的完整示例请见本主题中的示例 3。
示例 1
下面的示例说明包含两个类构造函数的类:一个类构造函数没有参数,另一个类构造函数带有两个参数。


class CoOrds
{
  public int x, y;

  // Default constructor:
  public CoOrds()
  {
    x = 0;
    y = 0;
  }

  // A constructor with two arguments:
  public CoOrds(int x, int y)
  {
    this.x = x;
    this.y = y;
  }

  // Override the ToString method:
  public override string ToString()
  {
    return (String.Format("({0},{1})", x, y));
  }
}

class MainClass
{
  static void Main()
  {
    CoOrds p1 = new CoOrds();
    CoOrds p2 = new CoOrds(5, 3);

    // Display the results using the overriden ToString method:
    Console.WriteLine("CoOrds #1 at {0}", p1);
    Console.WriteLine("CoOrds #2 at {0}", p2);
    Console.ReadKey();
  }
}

输出:


 CoOrds #1 at (0,0)
 CoOrds #2 at (5,3)    

示例 2
在此示例中,类 Person 没有任何构造函数;在这种情况下,将自动提供默认构造函数,同时将字段初始化为它们的默认值。