新的关键字和隐藏方法 [英] new Keyword and Method Hiding

查看:168
本文介绍了新的关键字和隐藏方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

新的关键字用于隐藏基类实现相同的。但我不知道为什么下面的代码生成的输出作为基类

The new Keyword is used to hide the base class implementation of the same. But I am not sure why the following code produces the output as Baseclass

class Baseclass
{ 
    public void fun()
    { 
        Console.Write("Base class" + " ");
    } 
} 
class Derived1: Baseclass
{ 
    new void fun()
    {
        Console.Write("Derived1 class" + " "); 
    } 
} 
class Derived2: Derived1
{ 
    new void fun()
    { 
        Console.Write("Derived2 class" + " ");
    }
}
class Program
{ 
    public static void Main(string[ ] args)
    { 
        Derived2 d = new Derived2(); 
        d.fun(); 
    } 
} 

我们都躲藏的乐趣了Derived2,但仍执行基类被称为为何如此?我缺少的东西吗?

We are hiding the implementation of fun in derived2 but still Base class is called why so? Am I missing something?

推荐答案

Derived2.fun 是私有的(它是默认的访问修饰符该类型的成员)。这不是在类外可见。唯一可见的乐趣类的外部方法是 Baseclass.fun ,因此它被调用。

Derived2.funis private (it is the default access modifier of the members of the type). It is not visible outside the class. Only visible fun method outside the class is Baseclass.fun and thus it is invoked.

您需要让类之外的 Derived2.fun 可见,以获得预期的输出。您可以通过做到这一点使得它的公共/内部。

You need to make your Derived2.fun visible outside the class to get the expected output. You can do it by either making it public/internal.

这篇关于新的关键字和隐藏方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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