为什么从Parent类构造函数调用子类方法(C#覆盖) [英] Why child class method is Called from Parent class constructor ( C# overriding)

查看:88
本文介绍了为什么从Parent类构造函数调用子类方法(C#覆盖)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Parent类中有虚方法,我直接在Parent类构造函数中调用此方法。



现在当我创建子类的对象时,我将调试器放在默认的构造函数上,然后执行完整的子类的子类默认构造函数然后为什么输出显示子类的方法被覆盖。







i have virtual method in Parent class and i am calling this method directly in Parent class constructor.

now when i am creating the object of child class and i am putting the debugger on the default Constructor on both then before the Executing the complete Block of child class Default constructor then why the Output dispaly method of child class which is override.



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication
{
    public  class class1
    {
       public virtual void Display()
        {
            Console.WriteLine("In Side Parent class");
        }
       public class1()
        {
            Display();
        }
    }
    class Program : class1
    {
        public Program()
        {

        }
        public override void Display()
        {
          Console.WriteLine("Inside Chiled Class");
        }
        static void Main(string[] args)
        {
            Program p=new Program();
            Console.ReadLine();
        }
    }
}

推荐答案

因为它是虚拟的。你观察到的是OOP的核心,没有OOP就不能成为OOP。请参阅: http://en.wikipedia.org/wiki/Dynamic_dispatch [ ^ ]。



方法<$ c通过虚拟方法表间接调用$ c>显示: http: //en.wikipedia.org/wiki/Virtual_method_table [ ^ ]。



这使得后期绑定,因此多态成为可能:

http://en.wikipedia.org/wiki/Late_binding [ ^ ],

http://en.wikipedia.org/wiki/Polymorphism_%28computer_scie nce%29 [ ^ ]。



你的例子非常有趣:你偶然发现了OOP,这是一个非常随意的尝试。恭喜!不幸的是,相反的情况更典型:有些人设法使用类,继承,甚至使用虚拟这个词,但从不做任何OOP,有些人设法不使用多年。 :-(



-SA
Because it is virtual. What you observed is the heart of OOP, without it OOP could not be OOP. Please see: http://en.wikipedia.org/wiki/Dynamic_dispatch[^].

The method Display is called indirectly, via the virtual method table: http://en.wikipedia.org/wiki/Virtual_method_table[^].

This is what makes late binding and, hence, polymorphism possible:
http://en.wikipedia.org/wiki/Late_binding[^],
http://en.wikipedia.org/wiki/Polymorphism_%28computer_science%29[^].

You example is very funny: you discovered OOP by a chance, as a result of pretty much random try. Congratulations! Unfortunately, the opposite case is more typical: some people manage to use classes, inheritance, even use the word "virtual" but never do any OOP, some people manage not to get it for years. :-(

—SA


这篇关于为什么从Parent类构造函数调用子类方法(C#覆盖)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆