Явная реализация членов интерфейса с наследованием 


Мы поможем в написании ваших работ!



ЗНАЕТЕ ЛИ ВЫ?

Явная реализация членов интерфейса с наследованием



Явная реализация интерфейса позволяет программисту реализовать два интерфейса, имеющие одинаковые имена членов, и осуществить отдельную реализацию для каждого члена интерфейса. В данном примере отображаются размеры окна как в метрических, так и в британских единицах измерения. Класс "Box" реализует два интерфейса: IEnglishDimensions и IMetricDimensions, которые соответствуют различным системам измерения. Оба интерфейса имеют одинаковые имена членов: "Length" и "Width".

Пример

ß------


 

// Explicitly implement the members of IEnglishDimensions: float IEnglishDimensions.Length() { return lengthInches; } float IEnglishDimensions.Width() { return widthInches; } // Explicitly implement the members of IMetricDimensions: float IMetricDimensions.Length() { return lengthInches * 2.54f; } float IMetricDimensions.Width() { return widthInches * 2.54f; } static void Main() { // Declare a class instance box1: Box box1 = new Box(30.0f, 20.0f); // Declare an instance of the English units interface: IEnglishDimensions eDimensions = (IEnglishDimensions)box1; // Declare an instance of the metric units interface: IMetricDimensions mDimensions = (IMetricDimensions)box1; // Print dimensions in English units: System.Console.WriteLine("Length(in): {0}", eDimensions.Length()); System.Console.WriteLine("Width (in): {0}", eDimensions.Width()); // Print dimensions in metric units: System.Console.WriteLine("Length(cm): {0}", mDimensions.Length()); System.Console.WriteLine("Width (cm): {0}", mDimensions.Width()); } }
Length(in): 30 Width (in): 20 Length(cm): 76.2 Width (cm): 50.8

 


 

ß----


Robust Programming

If you want to make the default measurements in English units, implement the methods Length and Width normally, and explicitly implement the Length and Width methods from the IMetricDimensions interface:

// 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; }

In this case, you can access the English units from the class instance and access the metric units from the interface instance:

public static void Test() { Box box1 = new Box(30.0f, 20.0f); IMetricDimensions mDimensions = (IMetricDimensions)box1; System.Console.WriteLine("Length(in): {0}", box1.Length()); System.Console.WriteLine("Width (in): {0}", box1.Width()); System.Console.WriteLine("Length(cm): {0}", mDimensions.Length()); System.Console.WriteLine("Width (cm): {0}", mDimensions.Width()); }

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

Если необходимо произвести измерения по умолчанию в британских единицах, реализуйте методы "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.

 


Параметры методов

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

Параметры, принимаемые методом, также указываются в скобках, но при этом необходимо указать имя и тип каждого из параметров. Это имя не обязательно должно совпадать с именем передаваемого аргумента. Пример.

public static void PassesInteger() { int fortyFour = 44; TakesInteger(fortyFour); } static void TakesInteger(int i) { i = 33; }

В этом примере метод с именем PassesInteger передает аргумент методу с именем TakesInteger. Внутри метода PassesInteger этот аргумент имеет имя fortyFour, но в методе TakeInteger он является параметром с именем i. Этот параметр существует только в методе TakesInteger. Именем i можно обозначить произвольное количество других переменных, и они могут иметь любой тип, если только они не являются параметрами или переменными, объявляемыми внутри этого метода.

Обратите внимание, что метод TakesInteger присваивает переданному аргументу новое значение. Можно предположить, что это изменение отразится на переменной метода PassesInteger после выполнения метода TakeInteger, но на самом деле значение переменной fortyFour останется неизменным. Это связано с тем, что тип int является типом значения. По умолчанию при передаче методу типа значения передается копия объекта, а не сам объект. Поскольку метод работает с копией, изменения параметра не оказывают влияния на значения переменной в вызывающем методе. Типы значения называются так потому, что вместо самого объекта передается копия этого объекта. То есть передается значение, а не объект.

Дополнительные сведения о передаче типов значений см. в разделе Передача параметров типа значения.

 


This differs from reference types, which are passed by reference. When an object that is based on a reference type is passed to a method, no copy of the object is made. Instead, a reference to the object that is being used as a method argument is made and passed. Changes made through this reference will therefore be reflected in the calling method. A reference type is created by using the class keyword as in the following example:

public class SampleRefType { public int value; }

Now, if an object that is based on this type is passed to a method, the object will be passed by reference. For example:

public static void TestRefType() { SampleRefType rt = new SampleRefType(); rt.value = 44; ModifyObject(rt); System.Console.WriteLine(rt.value); } static void ModifyObject(SampleRefType obj) { obj.value = 33; }

This example essentially does the same thing as the previous example. But, because a reference type is used, the modification made by ModifyObject is made to the object that is created in the TestRefType method. The TestRefType method will therefore display the value 33.

 


Эти типы отличаются от ссылочных типов, для которых значения передаются по ссылке. При передаче методу объекта, имеющего ссылочный тип, копия объекта не создается. Вместо этого создается и передается ссылка на объект, используемый в качестве аргумента метода. Изменения объекта, осуществляемые с помощью этой ссылки, будут доступны и в вызывающем методе. В следующем примере ключевое слово class указывает на то, что создается объект ссылочного типа.

public class SampleRefType { public int value; }

Теперь при передаче методу объекта этого типа объект будет передаваться по ссылке. Пример.

public static void TestRefType() { SampleRefType rt = new SampleRefType(); rt.value = 44; ModifyObject(rt); System.Console.WriteLine(rt.value); } static void ModifyObject(SampleRefType obj) { obj.value = 33; }

В этом примере выполняются те же действия, что и в предыдущем примере. Но поскольку используется ссылочный тип, изменения в методе ModifyObject относятся к объекту, созданному в методе created in the TestRefType. Поэтому в методе TestRefType на экран будет выведено значение 33.

Дополнительные сведения см. в разделе Передача параметров ссылочного типа.


Return Values

Methods can return a value to the caller. If the return type, the type listed before the method name, is not void, the method can return the value by using the return keyword. A statement with the return keyword followed by a value that matches the return type will return that value to the method caller. The return keyword also stops the execution of the method. If the return type is void, a return statement without a value is still useful to stop the execution of the method. Without the return keyword, the method will stop executing when it reaches the end of the code block. Methods with a non-void return type are required to use the return keyword to return a value. For example, these two methods use the return keyword to return integers:

class SimpleMath { public int AddTwoNumbers(int number1, int number2) { return number1 + number2; }   public int SquareANumber(int number) { return number * number; } }

To use a value returned from a method, the calling method can use the method call itself anywhere a value of the same type would be sufficient. You can also assign the return value to a variable. For example, the following two code examples accomplish the same goal:

int result = obj.AddTwoNumbers(1, 2); obj.SquareANumber(result);
obj.SquareANumber(obj.AddTwoNumbers(1, 2));

Using an intermediate variable, in this case, result, to store a value is optional. It may help the readability of the code, or it may be necessary if the value will be used more than one time.

Note:
A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to.

Возвращаемые значения

Методы могут возвращать значения вызывающим их объектам. Если тип возвращаемого значения, указываемый перед именем метода, не равен void, для возвращения значения используется ключевое слово return. В результате выполнения инструкции с ключевым словом return, после которого указано значение нужного типа, вызвавшему метод объекту будет возвращено это значение. Кроме того, ключевое слово return останавливает выполнение метода. Если тип возвращаемого значения void, инструкцию return без значения все равно можно использовать для завершения выполнения метода. Если ключевое слово return отсутствует, выполнение метода завершится, когда будет достигнут конец его блока кода. Для возврата значений методами с типом возвращаемого значения отличным от void необходимо обязательно использовать ключевое слово return. Например, в следующих двух методах ключевое слово return служит для возврата целочисленных значений.

ß------

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

int result = obj.AddTwoNumbers(1, 2); obj.SquareANumber(result);
obj.SquareANumber(obj.AddTwoNumbers(1, 2));

Использовать промежуточную переменную для хранения значения (в данном случае это переменная result) необязательно. Эта переменная может упростить восприятие кода либо быть необходимой, если значение потребуется использовать снова.

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

 


Passing Parameters

In C#, parameters can be passed either by value or by reference. Passing parameters by reference enables function members, methods, properties, indexers, operators, and constructors to change the value of the parameters and have that change persist. To pass a parameter by reference, use the ref or out keyword. For simplicity, only the ref keyword is used in the examples in this topic. For example:

// Passing by value static void Square(int x) { // code... }
// Passing by reference static void Square(ref int x) { // code... }

 


Передача параметров

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

// Passing by value static void Square(int x) { // code... }
// Passing by reference static void Square(ref int x) { // code... }

 



Поделиться:


Последнее изменение этой страницы: 2017-01-19; просмотров: 81; Нарушение авторского права страницы; Мы поможем в написании вашей работы!

infopedia.su Все материалы представленные на сайте исключительно с целью ознакомления читателями и не преследуют коммерческих целей или нарушение авторских прав. Обратная связь - 18.118.100.48 (0.038 с.)