Студопедия
Случайная страница | ТОМ-1 | ТОМ-2 | ТОМ-3
АрхитектураБиологияГеографияДругоеИностранные языки
ИнформатикаИсторияКультураЛитератураМатематика
МедицинаМеханикаОбразованиеОхрана трудаПедагогика
ПолитикаПравоПрограммированиеПсихологияРелигия
СоциологияСпортСтроительствоФизикаФилософия
ФинансыХимияЭкологияЭкономикаЭлектроника

Default constructors

Override methods | Extension methods | Method overloading | Static and instance properties | Virtual, sealed, override, and abstract accessors | Field-like events | Event accessors | Virtual, sealed, override, and abstract accessors | Indexer overloading | Conversion operators |


Читайте также:
  1. Default and Forfeiture
  2. Defining methods of object creation (constructors)
  3. Instance constructors
  4. Static constructors
  5. Определение значений по умолчанию с использованием блока defaultproperties

If a class contains no instance constructor declarations, a default instance constructor is automatically provided. That default constructor simply invokes the parameterless constructor of the direct base class. If the direct base class does not have an accessible parameterless instance constructor, a compile-time error occurs. If the class is abstract then the declared accessibility for the default constructor is protected. Otherwise, the declared accessibility for the default constructor is public. Thus, the default constructor is always of the form

protected C(): base() {}

or

public C(): base() {}

where C is the name of the class.

In the example

class Message
{
object sender;
string text;
}

a default constructor is provided because the class contains no instance constructor declarations. Thus, the example is precisely equivalent to

class Message
{
object sender;
string text;

public Message(): base() {}
}

Private constructors

When a class T declares only private instance constructors, it is not possible for classes outside the program text of T to derive from T or to directly create instances of T. Thus, if a class contains only static members and isn’t intended to be instantiated, adding an empty private instance constructor will prevent instantiation. For example:

public class Trig
{
private Trig() {} // Prevent instantiation

public const double PI = 3.14159265358979323846;

public static double Sin(double x) {...}
public static double Cos(double x) {...}
public static double Tan(double x) {...}
}

The Trig class groups related methods and constants, but is not intended to be instantiated. Therefore it declares a single empty private instance constructor. At least one instance constructor must be declared to suppress the automatic generation of a default constructor.

Optional instance constructor parameters

The this(...) form of constructor initializer is commonly used in conjunction with overloading to implement optional instance constructor parameters. In the example

class Text
{
public Text(): this(0, 0, null) {}

public Text(int x, int y): this(x, y, null) {}

public Text(int x, int y, string s) {
// Actual constructor implementation
}
}

the first two instance constructors merely provide the default values for the missing arguments. Both use a this(...) constructor initializer to invoke the third instance constructor, which actually does the work of initializing the new instance. The effect is that of optional constructor parameters:

Text t1 = new Text(); // Same as Text(0, 0, null)
Text t2 = new Text(5, 10); // Same as Text(5, 10, null)
Text t3 = new Text(5, 20, "Hello");


Дата добавления: 2015-11-16; просмотров: 63 | Нарушение авторских прав


<== предыдущая страница | следующая страница ==>
Instance constructors| Static constructors

mybiblioteka.su - 2015-2024 год. (0.008 сек.)