C# 29.10.2023
This commit is contained in:
parent
0bbcadd1d1
commit
8bd0095d45
57
C#/C#.md
57
C#/C#.md
@ -672,7 +672,7 @@ readonly struct Person2 {
|
||||
## Наследование
|
||||
|
||||
```C#
|
||||
Employee tom = new Employee();
|
||||
Employee tom = new Employee("Tom", "Org");
|
||||
tom.Name = "Tom";
|
||||
tom.PrintName();
|
||||
|
||||
@ -704,3 +704,58 @@ sealed class Employee: Person { // sealed запрещает наследова
|
||||
```
|
||||
|
||||
От статических классов тоже нельзя наследоваться.
|
||||
|
||||
## Преобразование типов
|
||||
|
||||
Все классы наследуются от Object. Upcasting - неявное преобразование к типу, который находится вверху иерархии классов. Downcasting - явное преобразование типа к производному
|
||||
|
||||
```C#
|
||||
Employee tom = new Employee("Tom", "Org");
|
||||
tom.Name = "Tom";
|
||||
Person person = tom;
|
||||
Employee employee = (Employee)person;
|
||||
Employee? employee = person as Employee; // null если преобразовать не удалось
|
||||
|
||||
class Person {
|
||||
private string _name = "";
|
||||
|
||||
public string Name {
|
||||
get { return _name; }
|
||||
set { _name = value }
|
||||
}
|
||||
|
||||
public Person(string name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public void PrintName() {
|
||||
Console.WriteLine(_name)
|
||||
}
|
||||
}
|
||||
|
||||
sealed class Employee: Person {
|
||||
public string company;
|
||||
|
||||
public Employee(string name, string company) : base(name) {
|
||||
this.company = company;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Переопределение
|
||||
|
||||
> Возможность изменить функцианальность метода родительского класса в дочернем. *virtual* помечает метод для переопределения в базовом классе, а *override* используется в дочернем
|
||||
|
||||
```C#
|
||||
class Foo {
|
||||
public virtual void func() {
|
||||
Console.WriteLine("Foo")
|
||||
}
|
||||
}
|
||||
|
||||
class Bar: Foo {
|
||||
public override void func() {
|
||||
Console.WriteLine("Bar")
|
||||
}
|
||||
}
|
||||
```
|
||||
|
Reference in New Issue
Block a user