创建的类型&lt的变量;基类>存储<派生类>对象在C# [英] Creating variable of type <base class> to store <derived class> object in C#

查看:87
本文介绍了创建的类型&lt的变量;基类>存储<派生类>对象在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*

这混淆了我,因为我不明白为什么有人会造成动物类型的变量存储类型猫的对象。为什么不一个人根本写:

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();



我不明白为什么它是合法的存储在一个父类型变量的子对象,而不是为什么它的有用。是有史以来有一个很好的理由来存储在动物变量主场迎战一个对象变量?一个人可以给我一个例子吗?我敢肯定它是与多态性与方法重载(和/或方法隐藏),但我似乎无法环绕它我的头。在此先感谢!

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项目,你将已经使用了类似的,因为所有的控件派生的东西从控制。然后你会发现一个窗口有一个列表控件( this.Controls ),允许你访问一个窗口上的所有子控件一次。 。即可以隐藏所有的控件

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#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆