C# upcasting/downcasting inheritance
为什么testmapolma.feeded()不是由testmapolma调用的哺乳类方法?什么是试验哺乳动物?左边是表示类型还是右边?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | 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(); } } } |
您的
如果您定义的东西有点不同,并且隐藏了
在
您还可以将类
抽象方法被重写的方式与虚拟方法相同。这可以防止混淆,并突出显示任何被错误地忽略的方法。
Why does testMammal.BreastFeed() called by testMammal not call the
BreastFeed method of Mammals class?
What is the type of testMammal?
1 | Mammals |
Does the left side indicate type or the right side?
左侧是变量的类型。变量引用的对象可以是
这是:
1 | Mammals testMammal = (aWhale as Mammals); |
是一样的
1 |
对象是鱼,变量是哺乳动物类型。您只能调用