为什么testMammal调用的testMammal.BreastFeed()不调用Mammals类的BreastFeed方法?什么是testMammal?左侧是指示类型还是右侧? Mammals testMammal = (aWhale as Mammals)

using System;
using System.Collections.Generic;

namespace ConsoleApplication3
{
    class Mammals
    {
        public string age { get; set; }
        public virtual void BreastFeed()
        {
            Console.WriteLine("This animal Breastfeeds its young ones.");
        }
    }

    class Fish : Mammals
    {
        public int FinsNum { get; set; }
        public override void BreastFeed()
        {
            Console.WriteLine("This animal Breastfeeds its young ones fish style");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Fish aWhale = new Fish();
            //Mammals testMammal = (Mammals)aWhale;

            Mammals testMammal = (aWhale as Mammals);
            testMammal.BreastFeed();
        }
    }
}

最佳答案

为什么testMammal调用的testMammal.BreastFeed()不调用
  哺乳类的BreastFeed方法?


testMammal是强制转换为FishMammalsBreastFeed()将在Fish上调用


  什么是testMammal?


Mammals



  左侧是指示类型还是右侧?


左侧是变量的类型。变量引用的对象可以是Mammals或任何子类。

这个:

Mammals testMammal = (aWhale as Mammals);


是相同的

Mammals textMammal = new Fish();


对象是一条鱼,变量的类型是哺乳动物。您只能呼叫Mammals的公共成员,但任何被覆盖的成员将是Fish's成员。

关于c# - C#向上/向下继承,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20505604/

10-10 19:32