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

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

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

Код42

--------

Результат 1 Employee number: 101 Employee name: Claude Vige

Example 2

Description

This example demonstrates how to access a property in a base class that is hidden by another property that has the same name in a derived class.

Code

public class Employee

{

private string name;

public string Name

{

get { return name; }

set { name = value; }

}

}

public class Manager : Employee

{

private string name;

// Notice the use of the new modifier:

public new string Name

{

get { return name; }

set { name = value + ", Manager"; }

}

}

class TestHiding

{

static void Main()

{

Manager m1 = new Manager();

// Derived class property.

m1.Name = "John";

// Base class property.

((Employee)m1).Name = "Mary";

System.Console.WriteLine("Name in the derived class is: {0}", m1.Name);

System.Console.WriteLine("Name in the base class is: {0}", ((Employee)m1).Name);

}

}

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

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

Код

------

Output 2

Name in the derived class is: John, Manager

Name in the base class is: Mary

Code Disscussion

The following are important points in the previous example:

  • The property Name in the derived class hides the property Name in the base class. In such a case, the new modifier is used in the declaration of the property in the derived class:

    public new string Name

  • The cast (Employee) is used to access the hidden property in the base class:

((Employee)m1).Name = "Mary";

Результат 2

Name in the derived class is: John, Manager

Name in the base class is: Mary

Рассмотрение кода

Далее перечислены важные замечания по предыдущему примеру:

  • Свойство Name в производном классе скрыто свойством Name в базовом классе. В этом случае модификатор new используется в объявлении свойства в производном классе:

    public new string Name

  • Приведение (Employee) используется для доступа к скрытому свойству в базовом классе:

((Employee)m1).Name = "Mary";

Example 3

Description

In this example, two classes, Cube and Square, implement an abstract class, Shape, and override its abstract Area property. Note the use of the override modifier on the properties. The program accepts the side as an input and calculates the areas for the square and cube. It also accepts the area as an input and calculates the corresponding side for the square and cube.

Code

abstract class Shape

{

public abstract double Area

{

get;

set;

}

}

class Square : Shape

{

public double side;

public Square(double s) //constructor

{

side = s;

}

public override double Area

{

get

{

return side * side;

}

set

{

side = System.Math.Sqrt(value);

}

}

}