When a virtual function in a C# base class calls the virtual function of the base class, does it execute the corresponding function implemented by the derived class?

Answer :

        Yes.

        For example, there are two virtual functions A and B in the base class Base, and the derived class is Derive. The overridden function A is marked as A', and the overridden function B is marked as B', and B' will Execute the logic of base.B;

        In Base, B calls the logic of A, then when the outside calls B' of the derived class Derive, the logic of B is executed in B', and then B will executeA'’s code! Rather than the logic of A in the base class.

Code example:

        The following is a specific case where I encountered this problem:

        I wrote a BulletEmitter in Unity. There is the following code in the base class:

    public virtual void tt()
    {
        Debug.Log("调用到基类的啦");
    }
    public virtual void test()
    {
        tt();
    }

 The corresponding piece of code in the derived class is:

    public override void tt()
    {
        Debug.Log("调用派生类的啦!");

    }
    public override void test()
    {
        base.test();
    }

Then run it in Unity, assign the derived class instance to a base class reference, and then call the test() method of the base class reference. The result is:

Therefore, the above conjecture is verified.

Guess you like

Origin blog.csdn.net/HowToPause/article/details/134234554