Difference between shadowing and overriding in C#?

后端 未结 6 811
面向向阳花
面向向阳花 2020-11-22 07:25

What\'s difference between shadowing and overriding a method in C#?

6条回答
  •  终归单人心
    2020-11-22 07:46

    If there is a case in which you cannot alter the contents of a class, let's say A, but you want to use its some methods along with you have a method which name is common, you can use your own method implementation by the new keyword.

    The crux point is to use it that both the reference and object must be of the same type.

    class A
    {
        public void Test()
        {
            Console.WriteLine("base");
        }
    }
    
    class B : A
    {
        public new void Test()
        {
            Console.WriteLine("sub");
        }
    
        public static void Main(string[] args)
        {
            A a = new A();
            B aa = new B();
            a.Test();
            aa.Test();
        }
    }
    

提交回复
热议问题