C# overload with override

半世苍凉 提交于 2019-12-02 12:14:06

Overridden methods are excluded from method set when compiler determines which method to call. See member lookup algorithm. So, when you call methodA on type B, set of members with name methodA from type B and it's base type will be constructed:

override B.methodA(AA)
virtual A.methodA(AA)
virtual A.methodA(BB)

Then members with ovveride modifier removed from set:

virtual A.methodA(AA)
virtual A.methodA(BB)

This group of methods is the result of lookup. After that overload resolution applied to define which member to invoke.

  1. A.methodA(BB) is invoked, because its argument matches parameter.
  2. A.methodA(AA) will be chosen, but it is virtual method, so actually call goes to B.method(AA)
  3. Same as option 2

No, it is entirely predictable. The method signature is resolved first - that is, the overload is determined first. Then, the most overridden method is called. So the output will be:

  • A:methodA(BB) called
  • B:methodA(AA) called
  • B:methodA(AA) called

The method taking an instance of AA will be called in the second two cases, because this is the type of the reference that is passed in, and it is B's version that is called. Note that even this would produce the same result:

A instance = new B();
instance.methodA((AA)new BB()); // Case 3

I think the result will be this

case 1 : Console.Write("A:methodA(BB) called");

case 2 : Console.Write("B:methodA(AA) called");

case 3 : Console.Write("B:methodA(AA) called");

in case 3 it will look the type that it's passed, and it's B

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!