多态和方法隐藏问题 - 创建对象集合以打印所有类方法 [英] Polymorphism and Method Hiding question - create object collection to print all class method

查看:65
本文介绍了多态和方法隐藏问题 - 创建对象集合以打印所有类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下课程,我们可以创建这些课程吗?



1.任何对象集合

2.使用该对象集合我可以打印所有类Hello方法。



I have Below classes and using these classes can we create?

1. Any collection of objects
2. Using that object collection i can print all class Hello method.

class First
{
    public virtual void Hello()
    {
        Console.Write("First \n");
    }
}
class Second : First
{
    public override void Hello()
    {
        Console.Write("Second \n");
    }
}
class Third : First
{
    public new void Hello()
    {
        Console.Write("Third \n");
    }
}

我试过这样但是它输出为

首先

第二

首先

I tried like this but it is giving output as
First
Second
First

static void Main(string[] args)
{
     List<First> lst = new List<First>();
     lst.Add(f);
     Second s = new Second();
     lst.Add(s);
     Third t = new Third();
     lst.Add(t);

     foreach (First obj in lst)
     {
         obj.Hello();
     }
     Console.ReadKey();
 }



但是我们需要输出为

第一次

第二次
第三个

推荐答案

你的问题是你忘记覆盖 Hello 中的第三个类,如第二个类。



现在,在第三个类中,您使用 new 关键字,这将隐藏基类中的继承方法。在以下情况下它会正常工作: t.Hello();



但是在你的代码中你试图在对象列表(多态)的上下文中使用,并且 override 关键字的使用对于多态是必需的。
Your problem is that your forgot to override the method Hello in your Third class like in your Second class.

Now, in your Third class you are using new keyword and this will hide the inherited method from your base class. And it will work fine in the case of: t.Hello();

But in your code you are trying to use in the context of a list of objects (polymorphism) and the usage of override keyword is mandatory for polymorphism.


这篇关于多态和方法隐藏问题 - 创建对象集合以打印所有类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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