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

Пример 2 Описание

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

Код

----

Partial Methods

A partial class or struct may contain a partial method. One part of the class contains the signature of the method. An optional implementation may be defined in the same part or another part. If the implementation is not supplied, then the method and all calls to the method are removed at compile time.

Partial methods enable the implementer of one part of a class to define a method, similar to an event. The implementer of the other part of the class can decide whether to implement the method or not. If the method is not implemented, then the compiler removes the method signature and all calls to the method. Therefore, any code in the partial class can freely use a partial method, even if the implementation is not supplied. No compile-time or run-time errors will result if the method is called but not implemented.

Partial methods are especially useful as a way to customize generated code. They allow for a method name and signature to be reserved, so that generated code can call the method but the developer can decide whether to implement the method. Much like partial classes, partial methods enable code created by a code generator and code created by a human developer to work together without run-time costs.

A partial method declaration consists of two parts: the definition, and the implementation. These may be in separate parts of a partial class, or in the same part. If there is no implementation declaration, then the compiler optimizes away both the defining declaration and all calls to the method.

// Definition in file1.cs

partial void onNameChanged();

// Implementation in file2.cs

partial void onNameChanged()

{

// method body

}

  • Partial method declarations must begin with the contextual keyword partial and the method must return void.

  • Partial methods can have ref but not out parameters.

  • Partial methods are implicitly private, and therefore they cannot be virtual.

  • Partial methods cannot be extern, because the presence of the body determines whether they are defining or implementing.

  • Partial methods can have static and unsafe modifiers.

  • Partial methods can be generic. Constraints are put on the defining partial method declaration, and may optionally be repeated on the implementing one. Parameter and type parameter names do not have to be the same in the implementing declaration as in the defining one.

  • You cannot make a delegate to a partial method.

Разделяемые методы

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

Разделяемые методы позволяют разработчику одной части класса определить метод, схожий с событием. Разработчик другой части класса может решить, реализовывать этот метод или нет. Если метод не реализован, то компилятор удаляет подпись метода и все вызовы этого метода. Таким образом, любой код в разделяемом классе может свободно использовать разделяемый метод, даже если реализация не предоставлена. Во время компиляции и выполнения программы не возникнут никакие ошибки, если метод будет вызван, но не реализован.

Разделяемые методы особенно полезны для настройки автоматически созданного кода. Они позволяют зарезервировать имя и подпись метода, чтобы автоматически созданный код мог вызвать метод, а разработчик мог сам решить, реализовывать этот метод или нет. Как и разделяемые классы, разделяемые методы позволяют организовать совместную работу автоматически созданного кода и кода, созданного человеком, без дополнительных затрат во время выполнения.

Объявление разделяемого метода состоит из двух частей: определения и реализации. Они могут находиться в разных частях или в одной и той же части разделяемого класса. Если объявление реализации отсутствует, то компилятор оптимизирует код, удаляя как объявление определения, так и все вызовы метода.

----

  • Объявления разделяемого метода должны начинаться с контекстно-зависимого ключевого слова partial, а метод должен возвращать значение типа void.

  • Разделяемые методы могут иметь параметры ref, но не могут иметь параметры out.

  • Разделяемые методы неявно имеют модификатор private и поэтому не могут иметь модификатор virtual.

  • Разделяемые методы не могут иметь модификатор extern, поскольку наличие тела определяет, выполняется ли их определение или реализация.

  • Разделяемые методы могут иметь модификаторы static и unsafe.

  • Разделяемые типы могут быть универсальными. Ограничения помещаются в ту часть обяъвления разделяемого метода, где находится определение, и могут дополнительно повторяться в разделе реализации. Имена параметров и типов параметров необязательно должны совпадать в объявлении реализации и в объявлении определения.

  • Нельзя использовать delegate в качестве разделяемого метода.

Static Classes and Static Class Members

Static classes and class members are used to create data and functions that can be accessed without creating an instance of the class. Static class members can be used to separate data and behavior that is independent of any object identity: the data and functions do not change regardless of what happens to the object. Static classes can be used when there is no data or behavior in the class that depends on object identity.

Static Classes

A class can be declared static, which indicates that it contains only static members. It is not possible to use the new keyword to create instances of a static class. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

Following are the main features of a static class:

  • They only contain static members.

  • They cannot be instantiated.

  • They are sealed.

  • They cannot contain Instance Constructors.

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor.