使用基类指向派生类有什么好处?

时间:2017-09-06 14:21:15

标签: c# inheritance

class Food
{
    public Food()
    {
        Console.WriteLine("This is original food");
    }
    public void sayCheese(string s)
    {
        Console.WriteLine(s + " this is from the base");
    }
    public virtual void randomMethod()
    {
        Console.WriteLine("This is from a base class");
    }
}
class Meal : Food
{
    public Meal()
    {
        Console.WriteLine("This is an original meal");
    }
    public new void sayCheese(string s)
    {
        Console.WriteLine(s + " this is from the child");
    }
    public override void randomMethod()
    {
        Console.WriteLine("This is from a child class");
    }
}
class Program
{
    static void Main(string[] arg)
    {
        Food basePointbase = new Food(); //base class pointing at base object
        Food basePointChild = new Meal(); //base class pointing at child object
        Meal childPointChild = new Meal(); //child class pointing at child object
        basePointbase.sayCheese("basefrombase"); //will call the base's method
        basePointChild.sayCheese("basefromchild"); //will call the base's method
        childPointChild.sayCheese("childfromchild"); //will call the child's method
        basePointbase.randomMethod(); //will call base's method 
        basePointChild.randomMethod(); //will call child's method
        childPointChild.randomMethod(); //will call child's method
    }
}

我承认的事情:

  1. 如果我要创建一个Child对象,我将调用base的构造函数和子代。
  2. 如果父类指向派生类,则将调用隐藏方法(通常隐藏在基类中)。
  3. 如果父类指向派生类,则将调用重写的方法(通常从子类重写)。
  4. 是的,这很清楚。但似乎有点不对劲。难道不仅仅是那个吗?指点如何工作?父进程指向子进程时编译器会发生什么?它是如何产生差异而不是实例化具有指向它的同一类的对象?

    编辑:我问的是基类指针如何影响除调用隐藏方法之外的任何东西。链接的问题根本没有显示出这些差异。请在将其标记为重复之前阅读该问题。

0 个答案:

没有答案