TOC

This article is currently in the process of being translated into Chinese (~3% done).

类 :

Constructors and destructors

构造函数是特殊的函数,用于实例化一个类的对象。构造函数不会返回任何值,所以你无需为它定义返回值类型。我们通常这样定义一个普通函数:

public string Describe()

我们可以这样定义一个构造函数:

public Car()

在我们本章的例子中,我们有一个Car类,它的构造函数接受一个字符串类型的参数。当然,构造函数也可以被重载,这意味着我们可以定义多个构造函数,名称相同,但接受不同的参数。例如:

public Car()
{

}

public Car(string color)
{
    this.color = color;
}

一个构造函数可调用另外一个构造函数,这在某些情况下十分实用。例如:

public Car()
{
    Console.WriteLine("Constructor with no parameters called!");
}

public Car(string color) : this()
{
    this.color = color;
    Console.WriteLine("Constructor with color parameter called!");
}

If you run this code, you will see that the constructor with no parameters is called first. This can be used for instantiating various objects for the class in the default constructor, which can be called from other constructors from the class. If the constructor you wish to call takes parameters, you can do that as well. Here is a simple example:

public Car(string color) : this()
{
    this.color = color;
    Console.WriteLine("Constructor with color parameter called!");
}

public Car(string param1, string param2) : this(param1)
{

}

如果你调用包含2个参数的构造函数,第一个参数也会用于调用只包含1个参数的那个构造函数。

Destructors

Since C# is garbage collected, meaing that the framework will free the objects that you no longer use, there may be times where you need to do some manual cleanup. A destructor, a method called once an object is disposed, can be used to cleanup resources used by the object. Destructors doesn't look very much like other methods in C#. Here is an example of a destructor for our Car class:

~Car() 
{
    Console.WriteLine("Out..");
}

Once the object is collected by the garbage collector, this method is called.

This article has been fully translated into the following languages: Is your preferred language not on the list? Click here to help us translate this article into your language!