Output 1 Employee number: 101 Employee name: Claude Vige
Пример 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); } } } |
Пример 3
Описание
В данном примере два класса Cube и Square реализуют абстрактный класс Shape и переопределяют его абстрактное свойство Area. Обратите внимание на использование для свойств модификатора override. Программа принимает размер стороны в качестве входных данных и вычисляет площади квадрата и куба. Она также принимает площадь в качестве входных данных и вычисляет значение стороны квадрата и куба.
|
|
Код
ß-----
class Cube : Shape
{
public double side;
public Cube(double s)
{
side = s;
}
public override double Area
{
get
{
return 6 * side * side;
}
set
{
side = System.Math.Sqrt(value / 6);
}
}
}
class TestShapes
{
static void Main()
{
// Input the side:
System.Console.Write("Enter the side: ");
double side = double.Parse(System.Console.ReadLine());
// Compute the areas:
Square s = new Square(side);
Cube c = new Cube(side);
// Display the results:
System.Console.WriteLine("Area of the square = {0:F2}", s.Area);
System.Console.WriteLine("Area of the cube = {0:F2}", c.Area);
System.Console.WriteLine();
// Input the area:
System.Console.Write("Enter the area: ");
double area = double.Parse(System.Console.ReadLine());
// Compute the sides:
s.Area = area;
c.Area = area;
// Display the results:
System.Console.WriteLine("Side of the square = {0:F2}", s.side);
System.Console.WriteLine("Side of the cube = {0:F2}", c.side);
}
}
ß--------
Input
4 24 |
Output 3
Enter the side: 4
Area of the square = 16.00
Area of the cube = 96.00
Enter the area: 24
Side of the square = 4.90
Side of the cube = 2.00
Введенные данные
4 24 |
Результат 3
Enter the side: 4
Area of the square = 16.00
Area of the cube = 96.00
Enter the area: 24
Side of the square = 4.90
Side of the cube = 2.00
Interface Properties
Properties can be declared on an interface. The following is an example of an interface indexer accessor:
|
|
public interface ISampleInterface { // Property declaration: string Name { get; set; } } |
The accessor of an interface property does not have a body. Thus, the purpose of the accessors is to indicate whether the property is read-write, read-only, or write-only.
Example
In this example, the interface IEmployee has a read-write property, Name, and a read-only property, Counter. The class Employee implements the IEmployee interface and uses these two properties. The program reads the name of a new employee and the current number of employees and displays the employee name and the computed employee number.
You could use the fully qualified name of the property, which references the interface in which the member is declared. For example:
string IEmployee.Name { get { return "Employee Name"; } set { } } |
This is called Explicit Interface Implementation. For example, if the class Employee is implementing two interfaces ICitizen and IEmployee and both interfaces have the Name property, the explicit interface member implementation will be necessary. That is, the following property declaration:
string IEmployee.Name { get { return "Employee Name"; } set { } } |
Свойства интерфейса
Свойства можно объявлять в interface. Ниже приведен пример метода доступа индексатора интерфейса:
ß--
Метод доступа свойства интерфейса не имеет тела. Поэтому методы доступа предназначены для того, чтобы указывать, доступно ли свойство для чтения и записи, только для чтения или только для записи.
Пример
В приведенном ниже примере интерфейс IEmployee имеет свойство с доступом записи/чтения, Name, а также свойство только для чтения Counter. Класс Employee реализует интерфейс IEmployee и использует эти два свойства. Программа считывает имя нового сотрудника и текущее количество сотрудников и выводит имя сотрудника и его вычисленный номер.
|
|
Можно использовать полное имя свойства, которое ссылается на интерфейс, в котором объявлен член. Пример.
string IEmployee.Name { get { return "Employee Name"; } set { } } |
Это называется Явная реализация интерфейса. Например, если класс Employee реализует два интерфейса ICitizen и IEmployee, и оба интерфейса имеют свойство Name, то обязательна явная реализация члена интерфейса. То есть, следующее объявление свойства.
string IEmployee.Name { get { return "Employee Name"; } set { } } |
implements the Name property on the IEmployee interface, while the following declaration:
string ICitizen.Name { get { return "Citizen Name"; } set { } } |
implements the Name property on the ICitizen interface.
interface IEmployee
{
string Name
{
get;
set;
}
int Counter
{
get;
}
}
public class Employee : IEmployee
{
public static int numberOfEmployees;
private string name;
public string Name // read-write instance property
{
get
{
return name;
}
set
{
name = value;
}
}
private int counter;
public int Counter // read-only instance property
{
get
{
return counter;
}
}
public Employee() // constructor
{
counter = ++counter + numberOfEmployees;
}
}
реализует свойство Name для интерфейса IEmployee, а следующее объявление:
string ICitizen.Name { get { return "Citizen Name"; } set { } } |
реализует свойство Name в интерфейсе ICitizen.
ß-------[43]
class TestEmployee { static void Main() { System.Console.Write("Enter number of employees: "); Employee.numberOfEmployees = int.Parse(System.Console.ReadLine()); Employee e1 = new Employee(); System.Console.Write("Enter the name of the new employee: "); e1.Name = System.Console.ReadLine(); System.Console.WriteLine("The employee information:"); System.Console.WriteLine("Employee number: {0}", e1.Counter); System.Console.WriteLine("Employee name: {0}", e1.Name); } } |
210 Hazem Abolrous |
Sample Output
Enter number of employees: 210
Enter the name of the new employee: Hazem Abolrous
The employee information:
Employee number: 211
Employee name: Hazem Abolrous
ß----
Дата добавления: 2019-03-09; просмотров: 231; Мы поможем в написании вашей работы! |
Мы поможем в написании ваших работ!