Creating variable of type lt;base classgt; to store lt;derived classgt; object in C#(创建lt;基类gt;类型的变量存储lt;派生类gt;C#中的对象)
问题描述
我对编程有点陌生,我有一个关于 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#中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:创建<基类>类型的变量存储<派生类>C#中的对象
基础教程推荐
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
