c# - 关于继承

标签 c# inheritance

为什么这段代码会产生输出“Base class”而不是“Derived2 class”?

namespace TestConsoleApplication
{ 
    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(); 
        } 
    } 
}

最佳答案

因为您没有将该方法声明为公共(public)的。

您已经告诉它隐藏原始定义,而不是覆盖它 - 它会做,但默认访问修饰符是private,不是公开的

例如,当从 Derived2 中调用方法时:

class Derived2 : Derived1
{
    new void fun()
    {
        Console.Write("Derived2 class" + " ");
    }

    public void Test()
    {
        fun();
    }
}
class Program
{
    public static void Main(string[] args)
    {
        Derived2 d = new Derived2();
        d.Test(); //Prints 'Derived2 class'
    }
}

将其设置为 public 确实会在您的原始示例中打印 Derived2

public new void fun()
{
    Console.Write("Derived2 class" + " ");
}

关于c# - 关于继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37606471/

相关文章:

c++ - 使用 C++ 导出重载函数

sql - 如何获得 "inherit"UNIQUE 属性?

java - Spark : . saveAsTextFile 丢失 Java 对象的继承字段

c++ - 有没有办法让成员参数类型成为指向派生类的指针

c# - 将基类属性重写为派生类型并通过基类访问

c# - Entity Framework 错误 : The field "ForeignKey" is required EF

c# - C# winform 上的交互式谷歌地图

c# - Windows窗体的SQLite只能插入一个元素

C# Windows 窗体用户控件控件设计器支持

c# - 使用指向 C# 中的函数的指针作为参数调用 C++ 函数