Confusion about virtual/new/override

后端 未结 5 1448
暗喜
暗喜 2020-12-15 01:06

I am a bit confused about the virtual/new/override thing. Here\'s an example:

class A
{
    public virtual void mVVirt         


        
5条回答
  •  情话喂你
    2020-12-15 01:34

    UPDATE : For a more information about this language feature, see the follow-up question here: More about Virtual / new...plus interfaces!

    Jason's answer is correct. To sum it up a bit more succinctly.

    You have three methods. Call them MA, MB and MC.

    You have two "boxes", or, as they're usually called, slots. We'll stick with Jason's nomenclature. Call them BOX1 and BOX2.

    "A" defines BOX1.

    "B" defines BOX2.

    "C" defines no box; it reuses BOX2.

    When you say "new A()", BOX1 is filled in with MA.

    When you say "new B()", BOX1 is filled in with MA and BOX2 is filled in with MB.

    When you say "new C()", BOX1 is filled in with MA and BOX2 is filled in with MC.

    Now suppose you have a variable of type A, and a call to the method. Reason like the compiler. The compiler says "are there any boxes on type A that match this name?" Yes, there is one: BOX1. Therefore, the compiler generates a call to the contents of BOX1.

    As we've seen, the contents of BOX1 is always MA, so MA is always called no matter whether the variable is actually holding a reference to A, B, or C.

    Now suppose you have a variable of type B, and a call to the method. Again, think like the compiler. The compiler says "are there any boxes on type B that matches this name?" Yes, there are TWO boxes that match by name. The compiler says "which of those two is more closely associated with B?" The answer is BOX2, because B declares BOX2. Therefore, the compiler generates a call to BOX2.

    This will call MB if the variable contains a B, because in a B, BOX2 contains MB. This will call MC if the variable contains a C, because in a C, BOX2 contains MC.

    Is that now clear? Remember, overload resolution just chooses the box. What the contents of the box are depend upon the object at runtime.

提交回复
热议问题