问题描述
我对编程有点陌生,我有一个关于 C# 中的类、继承和多态性的问题.在学习这些主题时,我偶尔会遇到如下代码:
I'm somewhat new to programming and I have a question about classes, inheritance, and polymorphism in C#. While learning about these topics, occasionally I'll come across code that looks something like this:
Animal fluffy = new Cat(); // where Animal is a superclass of Cat*
这让我很困惑,因为我不明白为什么有人会创建一个 Animal 类型的变量来存储 Cat 类型的对象.为什么一个人不简单地写这个:
This confuses me, because I don't understand why someone would create a variable of type Animal to store an object of type Cat. Why wouldn't a person simply write this:
Cat fluffy = new Cat();
我明白为什么将子对象存储在父类型变量中是合法的,但不明白为什么它有用.是否有充分的理由将 Cat
对象存储在 Animal
变量与 Cat
变量中?有人能给我举个例子吗?我确信它与多态性和方法覆盖(和/或方法隐藏)有关,但我似乎无法理解它.提前致谢!
I do understand why it's legal to store a child object in a parent type variable, but not why it's useful. Is there ever a good reason to store a Cat
object in an Animal
variable vs. a Cat
variable? Can a person give me an example? I'm sure it has something to do with polymorphism and method overriding (and/or method hiding) but I can't seem to wrap my head around it. Thanks in advance!
推荐答案
我能给你的最短的例子是如果你想要一个所有动物的列表
The shortest example I can give you is if you want a list of all animals
List<Animal> Animals = new List<Animal>();
Animals.Add(new Cat());
Animals.Add(new Dog());
如果您曾经使用 Winforms 创建过项目,那么您将已经使用过类似的东西,因为所有控件都派生自 Control
.然后您会注意到一个窗口有一个控件列表 (this.Controls
),它允许您一次访问窗口上的所有子控件.IE 隐藏所有控件.
If you have ever created a project using Winforms, you will have already used something similar since all controls derive from Control
. You will then notice that a Window has a list of controls (this.Controls
), that allows you to access all child controls on a window at once. I.E to hide all controls.
foreach(var control in this.Controls)
control.Hide();
这篇关于创建<基类>类型的变量存储<派生类>C#中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!