创建<基类>类型的变量存储<派生类>C#中的对象

Creating variable of type lt;base classgt; to store lt;derived classgt; object in C#(创建lt;基类gt;类型的变量存储lt;派生类gt;C#中的对象)
本文介绍了创建<基类>类型的变量存储<派生类>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();

这篇关于创建&lt;基类&gt;类型的变量存储&lt;派生类&gt;C#中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)