方法隐藏如何在C#中起作用?

Pra*_*ter 8 c# compiler-construction inheritance method-hiding

为什么打印以下程序

B
B
Run Code Online (Sandbox Code Playgroud)

(正如它应该)

public class A
    {
        public void Print()
        {
            Console.WriteLine("A");
        }
    }

    public class B : A
    {
        public new void Print()
        {
            Console.WriteLine("B");
        }

        public void Print2()
        {
            Print();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            var b = new B();
            b.Print();
            b.Print2();
        }
    }
Run Code Online (Sandbox Code Playgroud)

但如果我们删除B类中的关键字'public',就像这样:

    new void Print()
    {
        Console.WriteLine("B");
    }
Run Code Online (Sandbox Code Playgroud)

它开始打印

A
B
Run Code Online (Sandbox Code Playgroud)

Joe*_*orn 20

当你删除public访问修饰符时,你删除任何new Print()Main函数调用B的方法的能力,因为它现在默认为private.Main不再可以访问它了.

唯一剩下的选择是回退到从A继承的方法,因为这是唯一可访问的实现.如果您要从另一个B方法中调用Print(),您将获得B实现,因为B的成员将看到私有实现.


bdu*_*kes 5

您正在制作该Print方法private,因此唯一可用的Print方法是继承方法.