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

Результат

CoOrds 1: x = 0, y = 0

CoOrds 2: x = 10, y = 10

Example 2

Description

This example demonstrates a feature that is unique to structs. It creates a CoOrds object without using the new operator. If you replace the word struct with the word class, the program will not compile.

Code

public struct CoOrds

{

public int x, y;

public CoOrds(int p1, int p2)

{

x = p1;

y = p2;

}

}

// Declare a struct object without "new."

class TestCoOrdsNoNew

{

static void Main()

{

// Declare an object:

CoOrds coords1;

// Initialize:

coords1.x = 10;

coords1.y = 20;

// Display results:

System.Console.Write("CoOrds 1: ");

System.Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);

}

}

Output

CoOrds 1: x = 10, y = 20

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

В следующем примере демонстрируется уникальная возможность структур. В нем создается объект CoOrds без использования оператора new. Если заменить слово struct словом class, программа не будет скомпилирована.

Код

----

Результат

CoOrds 1: x = 10, y = 20

Inheritance

Classes can inherit from another class. This is accomplished by putting a colon after the class name when declaring the class, and naming the class to inherit from—the base class—after the colon, as follows:

public class A

{

public A() { }

}

public class B : A

{

public B() { }

}

The new class—the derived class—then gains all the non-private data and behavior of the base class in addition to any other data or behaviors it defines for itself. The new class then has two effective types: the type of the new class and the type of the class it inherits.

In the example above, class B is effectively both B and A. When you access a B object, you can use the cast operation to convert it to an A object. The B object is not changed by the cast, but your view of the B object becomes restricted to A's data and behaviors. After casting a B to an A, that A can be cast back to a B. Not all instances of A can be cast to B—just those that are actually instances of B. If you access class B as a B type, you get both the class A and class B data and behaviors. The ability for an object to represent more than one type is called polymorphism.

Structs cannot inherit from other structs or classes. Both classes and structs can inherit from one or more interfaces.

Наследование

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

public class A

{

public A() { }

}

public class B : A

{

public B() { }

}

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

В приведенном выше примере класс B является одновременно классом B и классом A. При доступе к объекту можно выполнить операцию приведения для преобразования его в объект класса A. При выполнении операции приведения исходный объект класса B не изменяется, но он ограничивается данными и поведением объекта класса A. После приведения объекта B к A этот объект A не может быть приведен обратно к B. Не все экземпляры A могут быть приведены к B — только те, которые фактически являются экземплярами B. При доступе к классу B как к типу B вы получаете данные и поведение одновременно класса A и B. Способность объекта представлять более чем один тип называется полиморфизмом. Дополнительные сведения см. в разделе Полиморфизм. Дополнительные сведения об операции приведения см. в разделе Приведение.

Структуры не могут наследовать от других структур или классов. Как классы, так и структуры способны наследовать от одного или нескольких интерфейсов. Дополнительные сведения см. в разделе Интерфейсы.

Abstract and Sealed Classes and Class Members

The abstract keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract classes. The sealed keyword enables you to prevent the inheritance of a class or certain class members that were previously marked virtual.

Abstract Classes and Class Members

Classes can be declared as abstract. This is accomplished by putting the keyword abstract before the keyword class in the class definition. For example:

public abstract class A

{

// Class members here.

}

An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class.

Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method. For example:

public abstract class A

{

public abstract void DoWork(int i);

}