继承如何在C#中工作

时间:2019-03-03 18:26:56

标签: c# oop inheritance

我有一个密码

using System;

namespace ExploreOOP
{
    class Program
    {
        static void Main(string[] args)
        {    
            Base1 b1 = new Derived1();
            Derived1 d1 = new Derived1();
            b1.write();
            d1.write();

            Console.WriteLine();
            Console.WriteLine();


            Base2 b2 = new Derived2();
            Derived2 d2 = new Derived2();
            b2.write();
            d2.write();


            Console.WriteLine();
            Console.WriteLine();

            Base3 b3 = new Derived3();
            Derived3 d3 = new Derived3();
            b3.write();
            d3.write();

            Console.ReadKey();

        }
    }

    public class Base1
    {
        public void write()
        {
            Console.WriteLine("Inside Base1 class");
        }
    }

    public class Derived1 : Base1
    {
        public void write()
        {
            Console.WriteLine("Inside Derived1 class");
        }
    }

    public class Base2
    {
        public virtual void write()
        {
            Console.WriteLine("Inside Base2 class");
        }
    }

    public class Derived2 : Base2
    {
        public override void write()
        {
            Console.WriteLine("Inside Derived2 class");
        }
    }

    public class Base3
    {
        public void write()
        {
            Console.WriteLine("Inside Base3 class");
        }
    }

    public class Derived3 : Base3
    {
        new public void write()
        {
            Console.WriteLine("Inside Derived3 class");
        }
    }

}

它会输出

Inside Base1 class
Inside Derived1 class


Inside Derived2 class
Inside Derived2 class


Inside Base3 class
Inside Derived3 class

所以我的问题是,

public class Base1
{
    public void write()
    {
        Console.WriteLine("Inside Base1 class");
    }
}

public class Derived1 : Base1
{
    public void write()
    {
        Console.WriteLine("Inside Derived1 class");
    }
}

public class Base3
{
    public void write()
    {
        Console.WriteLine("Inside Base3 class");
    }
}

public class Derived3 : Base3
{
    new public void write()
    {
        Console.WriteLine("Inside Derived3 class");
    }
}

是同一回事吗?

1 个答案:

答案 0 :(得分:2)

根据new modifier上的C#参考:

  

当用作声明修饰符时,new关键字显式隐藏从基类继承的成员。隐藏继承的成员时,成员的派生版本将替换基类版本。尽管可以在不使用new修饰符的情况下隐藏成员,但是会收到编译器警告。如果使用new显式隐藏成员,则它会禁止显示此警告。

这意味着是的,Derived3Derived1基本相同,除了第一种情况将输出警告,特别是

warning CS0108: 'Derived1.write()' hides inherited member 'Base1.write()'. Use the new keyword if hiding was intended.