TOC

This article is currently in the process of being translated into Chinese (~12% 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

C#有自动垃圾回收功能,意思是当你不再使用某些对象时,系统会自动释放它们使用的内存. 有时候你可能需要一些定制化的清理动作, 这就是析构函数的作用. 它是当对象不再使用时被调用的函数, 会清理对象所占用的资源. 析构函数和C#中的其他方法看起来不太一样.下面的例子是我们定义的类Car的析构函数:

~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!