需要帮助了解多态性的使用 [英] Need help understanding the use of Polymorphism

查看:74
本文介绍了需要帮助了解多态性的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我知道理论上的多态性.
我想了解的是例如;

Ok I know what polymorphism is in theory.
What I would like to understand is for example;

Public Class DerivedClass
      Inherits BaseClass

      Public Function Do() As BaseClass
        ''Code to do something and return a value
      End Function
End Class



我知道我的例子不是很广泛,但是我想尝试理解这个版本的多态性是如何工作的,它是否(取决于函数中编写的代码)返回正确的派生类.您能给我一个简单的工作示例吗?



I know that my example is not very expansive, but I am looking to try and understand is how this version of polymorphism works, does it (depending on the code writen within the function) return the correct derived class. Can you give me a simple working example on how it works.

Thank You in advance!

推荐答案

概括Jpuckett的示例....

多态是一种层次分类系统.以生物学为例,您可以创建一个类LivingThing,该类对生物的所有特征进行编码:它可以吃,可以繁殖,可以适应.然后,创建从LivingThing继承的类PlantAnimal.植物和动物都在进食,繁殖和适应,但它们的行为有所不同.因此,Plant.Eat()Animal.Eat()的实现方式将有所不同.

同样,AnimalReptileMammal的基类.两种动物都吃相同的食物,因此都可以使用base Animal.Eat()方法.它们具有非常不同的复制方式,因此会有不同的Replicate()方法.连同不同的实现(Reptile使用Egg框架,而Mammal使用Placenta),Reptile.Replicate()将返回类型为Reptile的对象,而Mammal.Replicate()将返回类型为Mammal的对象

最终,您可以在最终从LivingThing派生的任何对象上调用Eat()Replicate().就用户/编码器而言,尽管内部实现不是必需的,但与父类无关,它们是相同的方法.相同的方法,不同的形式...多态性.
To generalize on Jpuckett''s example....

Polymorphism is a kind of hierarchic classification system. To use biology as an example, you can create a class LivingThing that encodes all the characteristics of living things: it eats, it reproduces, it adapts. You then create classes Plant and Animal which inherit from LivingThing. Both plants and animals eat, reproduce and adapt, but they do so differently; Plant.Eat() and Animal.Eat() would therefore be implemented differently.

Likewise, Animal is the base class for Reptile and and Mammal. Both types of animals eat the same, so both could use the base Animal.Eat() method. They have very different ways of reproducing, though and so would have different Replicate() methods. Along with the different implementations (Reptile uses the Egg framework while Mammal uses Placenta), Reptile.Replicate() would return an object of type Reptile while Mammal.Replicate() would return an object of type Mammal

Ultimately, you can call Eat() and Replicate() on any object ultimately derived from LivingThing. As far as the user/coder is concerned, they are the same methods regardless of the parent class, even though the internal implementation is not. Same method, different forms... polymorphism.



有直接关系
我知道我的示例不是很广泛,但是我想尝试理解这个版本的多态性是如何工作的,它是否(取决于函数中编写的代码)返回正确的派生类.您能给我一个简单的工作示例吗?

您可以在任何可以返回类似您所拥有类型的方法中编写方法.

公共函数Do()作为BaseClass
最终功能

此函数根本不必存在于派生类中.这一切都是返回一个对象.这将返回BaseClass类型的对象,就像Function FUBAR()一样,因为Int32将返回整数.
结束编辑



这是几年前我在MSDN上看到的一个很好的例子.

世界上的每只猫都是猫.它也是一种动物.这也是一种生物.但是,并不是每只猫都是一样的.请看下面的例子.


In direct relation to

I know that my example is not very expansive, but I am looking to try and understand is how this version of polymorphism works, does it (depending on the code writen within the function) return the correct derived class. Can you give me a simple working example on how it works.

You can write a method anywhere that returns a type like what you have.

Public Function Do() As BaseClass
End Function

This function doesn''t have to exist in the derived class at all. All this does is return an object. This would return the object of type BaseClass just like a Function FUBAR() As Int32 would return an integer.
END EDIT



Here''s a nice example that I think I saw on MSDN a couple years back.

Every cat in the world is a Cat. It''s also an animal. It''s also a living thing. But not every cat is the same. Take the following example.


public class Cat
    {
        public string Genus { get; set; }
        public string Species { get; set; }
        public void Eat(object something)
        {
            //Eat something.
        }
        public void Sleep(int hours)
        {
            //Sleep is essential
        }
        public void BodilyFunctions()
        {
            //All cats do this
        }
    }

    public class Tiger : Cat
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public Tiger()
        {
            Genus = "Panthera";
            Species = "tigris";
        }

        public void GoHunting()
        {
            Eat("Human");
            Sleep(9);
            BodilyFunctions();
        }

        public void BeLazyBecauseItsHotInIndia()
        {
            Sleep(12);
        }
    }

    public class HouseCat : Cat
    {
        /// <summary>
        /// Constructor
        /// </summary>
        public HouseCat()
        {
            Genus = "Felis";
            Species = "catus";
        }

        public void EatFromTheBowl()
        {
            Eat("CatFood");
        }

        public void EverydayLife()
        {
            Purr();
            EatFromTheBowl();
            Purr();
            BeLazy();
            Purr();
        }

        public void BeLazy()
        {
            Sleep(12);
        }

        public void Purr()
        {
            //Make purring noise
        }
    }



家猫不吃人,但家猫和老虎都有属和种.现在从技术上讲,我应该在此处使用接口,因为家猫"和老虎"(is的谓词形式)都是猫,但是它们也都具有"属和种,因此适用.
这是什么意思?这意味着您的基类(在这种情况下应该是抽象的,但这是另一个讨论和研究的过程),可以通过更改其初始设置而变形并扩展为其他东西.但是,在.NET中只有一个继承,因此必须注意,当继承一个类时,您将继承该类的全部,并且这可能会改变您查看代码的方式.

ASP.NET MVC的共同点(真实示例)是将Controller用于站点的特定部分,例如需要身份验证的安全部分.您可以轻松地在每个控制器方法上放置一个装饰器,或者可以实现一个所有控制器都继承自的"BaseController",并在那里进行检查.您可能会因为类似的事情而看到那里的思想流派-不要重复自己.



House cats don''t eat people, but both house cats and tigers have a genus and a species. Now technically I should be using an Interface here because both House Cat and Tiger (be-verb-form of is) are Cats, but they also both "have" a genus and species, so this applies.

What does this mean? It means that your base class (which in this case SHOULD be abstract, but that''s another course of discussion and study), gets morphed and extended into other things by changing it''s initial setup. However, in .NET there is only single inheritance, so you must be mindful that when you inherit a class, you inherit the entirety of that class, and that can change the way you look at code.

An ASP.NET MVC commonality (a real-world example) is to use Controllers for particular sections of a site, say a secured section that requires authentication. You can just as easily put a decorator on each of your controller methods, or you can implement a "BaseController" that all controllers inherit from, and check there. The school of thought you might see out there for something like this is DRY -- don''t repeat yourself.


这篇关于需要帮助了解多态性的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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