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

Результат

Area of the circle = 19.63

Area of the cylinder = 86.39

Private Constructors

A private constructor is a special instance constructor. It is generally used in classes that contain static members only. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class. For example:

class NLog

{

// Private Constructor:

private NLog() { }

public static double e = System.Math.E; //2.71828...

}

The declaration of the empty constructor prevents the automatic generation of a default constructor. Note that if you do not use an access modifier with the constructor it will still be private by default. However, the private modifier is usually used explicitly to make it clear that the class cannot be instantiated.

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static.

Закрытые конструкторы35

Закрытый конструктор — это особый конструктор экземпляров. Обычно он используется в классах, содержащих только статические элементы. Если в классе один или несколько закрытых конструкторов и ни одного открытого конструктора, то прочие классы (за исключением вложенных классов) не смогут создавать экземпляры этого класса. Пример.

class NLog

{

// Private Constructor:

private NLog() { }

public static double e = System.Math.E; //2.71828...

}

Объявление пустого конструктора запрещает автоматическое создание конструктора по умолчанию. Обратите внимание, что если не использовать с конструктором модификатор доступа, то по умолчанию он все равно будет закрытым. Однако обычно используется модификатор private, чтобы ясно обозначить невозможность создания экземпляров данного класса.

Закрытые конструкторы используются, чтобы не допустить создание экземпляров класса при отсутствии полей или методов экземпляра, например для класса Math, или когда осуществляется вызов метода для получения экземпляра класса. Если все методы в классе являются статическими, имеет смысл сделать статическим весь класс. Дополнительные сведения см. в разделе Статические классы и члены статических классов.

Example

The following is an example of a class using a private constructor.

public class Counter

{

private Counter() { }

public static int currentCount;

public static int IncrementCount()

{

return ++currentCount;

}

}

class TestCounter

{

static void Main()

{

// If you uncomment the following statement, it will generate

// an error because the constructor is inaccessible:

// Counter aCounter = new Counter(); // Error

Counter.currentCount = 100;

Counter.IncrementCount();

System.Console.WriteLine("New count: {0}", Counter.currentCount);

}

}

Output

New count: 101

Notice that if you uncomment the following statement from the example, it will generate an error because the constructor is inaccessible because of its protection level:

// Counter aCounter = new Counter(); // Error

Пример

Ниже приведен пример класса с закрытым конструктором.

-------