Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
CSharp_Prog_Guide.doc
Скачиваний:
16
Добавлен:
16.11.2019
Размер:
6.22 Mб
Скачать

Результат

The static constructor invoked.

The Drive method invoked.

How to: Write a Copy Constructor

Unlike some languages, C# does not provide a copy constructor. If you create a new object and want to copy the values from an existing object, you have to write the appropriate method yourself.

Example

In this example, the Personclass contains a constructor that takes as the argument another object of type Person. The contents of the fields in this object are then assigned to the fields in the new object.

class Person

{

private string name;

private int age;

// Copy constructor.

public Person(Person previousPerson)

{

name = previousPerson.name;

age = previousPerson.age;

}

// Instance constructor.

public Person(string name, int age)

{

this.name = name;

this.age = age;

}

// Get accessor.

public string Details

{

get

{

return name + " is " + age.ToString();

}

}

}

class TestPerson

{

static void Main()

{

// Create a new person object.

Person person1 = new Person("George", 40);

// Create another new object, copying person1.

Person person2 = new Person(person1);

System.Console.WriteLine(person2.Details);

}

}

George is 40

Создание конструктора копии

В отличие от некоторых языков в C# отсутствует конструктор копии. Если создан новый объект и требуется скопировать значения из существующего объекта, необходимо создать соответствующий метод самостоятельно.

Пример

В данном примере Person класс содержит конструктор, который принимает другой объект типа Person в качестве аргумента. Содержимое полей в данном объекте назначается полям в новом объекте.

-----

Destructors

Destructors are used to destruct instances of classes.

Remarks

  • Destructors cannot be defined in structs. They are only used with classes.

  • A class can only have one destructor.

  • Destructors cannot be inherited or overloaded.

  • Destructors cannot be called. They are invoked automatically.

  • A destructor does not take modifiers or have parameters.

For example, the following is a declaration of a destructor for the class Car:

class Car

{

~ Car() // destructor

{

// cleanup statements...

}

}

The destructor implicitly calls Finalize on the base class of the object. Therefore, the previous destructor code is implicitly translated to the following code:

protected override void Finalize()

{

try

{

// Cleanup statements...

}

finally

{

base.Finalize();

}

}

This means that the Finalize method is called recursively for all instances in the inheritance chain, from the most-derived to the least-derived.