Зачем использовать virtual и override? - C#
Формулировка задачи:
Зачем использовать virtual и override, если и без них все замечательно работает, например:
выведет одно и то же если даже не подключать override и virtual, в чем же смысл.
Листинг программы
- class First {
- public virtual string Method()
- {
- return "text 1 method";
- }
- }
- class Next : First {
- public override string Method()
- {
- return "text 2 method";
- }
- }
- class Third : Next {
- public override string Method()
- {
- return "text 3 method";
- }
- }
- public static void Main()
- {
- First first = new First();
- Next next = new Next();
- Third third = new Third();
- Console.WriteLine(first.Method());
- Console.WriteLine(next.Method());
- Console.WriteLine(third.Method());
- }
- }
Решение задачи: «Зачем использовать virtual и override?»
textual
Листинг программы
- class First {
- public virtual string Method()
- {
- return "text 1 method";
- }
- }
- class Next : First {
- public override string Method()
- {
- return "text 2 method";
- }
- }
- class Third : Next {
- public override string Method()
- {
- return "text 3 method";
- }
- }
- public static void Main()
- {
- First first = new First();
- Next next = new Next();
- First third2 = new Third();
- Console.WriteLine(first.Method());
- Console.WriteLine(next.Method());
- Console.WriteLine(third2.Method());
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д