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

Надежное программирование

Если необходимо произвести измерения по умолчанию в британских единицах, реализуйте методы "Length" и "Width" в обычном режиме и явно реализуйте методы "Length" и "Width" из интерфейса IMetricDimensions:

// Normal implementation:

public float Length()

{

return lengthInches;

}

public float Width()

{

return widthInches;

}

// Explicit implementation:

float IMetricDimensions.Length()

{

return lengthInches * 2.54f;

}

float IMetricDimensions.Width()

{

return widthInches * 2.54f;

}

В этом случае можно получить доступ к британским единицам из экземпляра класса, а к метрическим единицам — из экземпляра интерфейса:

---

Members

Classes and structs have members that represent their data and behavior. The following table lists the members:

Member

Description

Fields

Fields are instances of objects that are considered part of a class, ordinarily holding class data. For example, a calendar class may have a field that contains the current date.

Properties

Properties are methods on a class that are accessed as if they were fields on that class. A property can provide protection for a class field to keep it from being changed without the knowledge of the object.

Methods

Methods define the actions that a class can perform. Methods can take parameters that provide input data, and can return output data through parameters. Methods can also return a value directly, without using a parameter.

Events

Events provide notifications about occurrences, such as button clicks or the successful completion of a method, to other objects. Events are defined and triggered by using delegates. For more information, see Events and Delegates.

Operators

Operators are terms or symbols such as +, *, <, and so on that perform operations on operands. Operators can be redefined to perform operations on custom data types.

Indexers

Indexers enable an object to be indexed in a manner similar to arrays.

Constructors

Constructors are methods that are called when the object is first created. They are often used to initialize the data of an object.

Destructors

Destructors are methods that are called by the runtime execution engine when the object is about to be removed from memory. They are generally used to make sure that any resources which must be released are handled appropriately.

Nested Types

Nested types are types declared in a class or struct. Nested types are often used to describe objects that are used only by the types that contain them.

Члены

В классах и структурах есть члены, представляющие их данные и поведение. Члены класса включают все члены, объявленные в этом классе, а также все члены (кроме конструкторов и деструкторов), объявленные во всех классах в иерархии наследования данного класса.

В следующей таблице перечислены виды членов, которые могут содержаться в классе или в структуре.

Член

Описание

Поля

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

Константы

Константы — это поля или свойства, значения которых устанавливаются во время компиляции и не изменяются.

Свойства

Свойства — это методы класса. Доступ к ним осуществляется так же, как если бы они были полями этого класса. Свойство может защитить поле класса от изменений (независимо от объекта).

Методы

Методы определяют действия, которые может выполнить класс. Методы могут получать параметры, предоставляющие входные данные, и возвращать выходные данные посредством параметров. Также методы могут возвращать значения напрямую, без использования параметров.

События

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

Операторы

При перегрузке оператора его следует определить как открытый статический метод в классе. Предопределенные операторы (+, *, < и т. д.) не считаются членами. Дополнительные сведения см. в разделе Перегружаемые операторы.

Индексаторы

Индексаторы позволяют индексировать объекты аналогично массивам.

Конструкторы

Конструкторы — это методы классов, вызываемые при создании объекта заданного типа. Зачастую они используются для инициализации данных объекта.

Деструкторы

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

Вложенные типы

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

Methods

A method is a code block that contains a series of statements. In C#, every executed instruction is performed in the context of a method. This topic discusses named methods. Another kind of method, called an anonymous function, is discussed elsewhere in the documentation.

Methods are declared in a class or struct by specifying the access level, the return value, the name of the method, and any method parameters. These parts together are the signature of the method. Method parameters are enclosed in parentheses and are separated by commas. Empty parentheses indicate that the method requires no parameters. This class contains three methods:

class Motorcycle

{

public void StartEngine() { }

public void AddGas(int gallons) { }

public int Drive(int miles, int speed) { return 0; }

}

Calling a method on an object is like accessing a field. After the object name, add a period, the name of the method, and parentheses. Arguments are listed within the parentheses, and are separated by commas. The methods of the Motorcycle class can therefore be called as in the following example:

Motorcycle moto = new Motorcycle();

moto.StartEngine();

moto.AddGas(15);

moto.Drive(5, 20);

Методы

Метод представляет собой блок кода, содержащий набор инструкций. В C# все инструкции выполняются в контексте метода. В этом разделе описываются именованные методы. Другой тип методов, называемых анонимными функциями, описан в других разделах документации.

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

class Motorcycle

{

public void StartEngine() { }

public void AddGas(int gallons) { }

public int Drive(int miles, int speed) { return 0; }

}

Вызов метода объекта очень похож на обращение к полю. После имени объекта ставится точка, затем имя метода и скобки. В скобках перечисляются аргументы, разделенные запятыми. Таким образом, методы класса Motorcycle можно вызывать так, как показано в следующем примере.

Motorcycle moto = new Motorcycle();

moto.StartEngine();

moto.AddGas(15);

moto.Drive(5, 20);

Method Parameters

As shown in the previous example, passing arguments to a method is just a matter of providing them in the parentheses when you call a method. To the method being called, the incoming arguments are called parameters.

The parameters that a method receives are also provided in a set of parentheses, but the type and a name for each parameter must be specified. The name does not have to be the same as the argument. For example:

public static void PassesInteger()

{

int fortyFour = 44;

TakesInteger(fortyFour);

}

static void TakesInteger(int i)

{

i = 33;

}

Here a method named PassesInteger passes an argument to a method named TakesInteger. Within PassesInteger, the argument is named fortyFour, but in TakeInteger, this is a parameter named i. This parameter exists only in the TakesInteger method. Any number of other variables can be named i, and they can be of any type as so long as they are not parameters or variables declared inside this method.

Notice that TakesInteger assigns a new value to the provided argument. One might expect this change to be reflected in the PassesInteger method after TakeInteger returns, but in fact the value in the variable fortyFour remains unchanged. This is because int is a value type. By default, when a value type is passed to a method, a copy is passed instead of the object itself. Because they are copies, changes to the parameter have no effect within the calling method. Value types get their name from the fact that a copy of the object is passed instead of the object itself. The value is passed, but not the same object.