C # succession overload and override

namespace ConsoleApp1
{

    public class A 
    {

        public void P() {
            Console.WriteLine("这里是A的PP哦!");
        }
        public void P(int a) { }
        public void P(bool a) { }
        public void P(int a, int b) { }

    }

    public class B : A
    {

        public new void P()
        {
            Console.WriteLine("这是B的PP!");
        }

    }
}
namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            _dictClass.Add(0, new A());
            _dictClass.Add(1, new B());

            _dictClass[0].P();
            _dictClass[1].P();
            (_dictClass[1] as B).P();

        }
        private static Dictionary<int, A> _dictClass = new Dictionary<int, A>();
    }

}

First explain override and overload

Translation and rewriting is called overloading my opinion, the difference between the two in terms of the performance of the two is obvious, first of all the code is written in the area, which overloaded in a class, rewriting is a subclass of the parent classes rewrite, then the performance of different priorities, rewriting performance takes precedence over the object to be rewritten, that priority performance that method rewritten

namespace ConsoleApp1
{

    public class A 
    {

        public virtual void P() {
            Console.WriteLine("这里是A的PP哦!");
        }
        public void P(int a) { }
        public void P(bool a) { }
        public void P(int a, int b) { }

    }

    public class B : A
    {

        public override void P()
        {
            Console.WriteLine ( " This is the PP B! " ); 
        } 

    } 
}

Under the code to do a little change, output:

P rewritten significantly higher priority to be rewritten P.

Note: When deep inheritance, rewrite manifested always the last to be rewritten.

Then he went on to say overloaded, the author summed up here, the type of the method in any case, as long as the same method name, it is a method, a method is overloaded direct impact inside the parameters, look at the definition of Wikipedia

"Overload, simply, function or method that has the same name, but not the same situation as the parameter list, function or method between such different parameters of the same name, referred to reload each function or method."

Look at the code prompt, not difficult to experiment or try their own.

Guess you like

Origin www.cnblogs.com/fairy-blonde/p/11567297.html