Why does this work? Method overloading + method overriding + polymorphism

后端 未结 4 1413
遇见更好的自我
遇见更好的自我 2020-12-17 17:30

In the following code:

public abstract class MyClass
{
public abstract bool MyMethod(
        Database database,
        AssetDetails asset,
        ref str         


        
4条回答
  •  情歌与酒
    2020-12-17 18:14

    Because that's the way the language is defined. For virtual members, the Implementation which is called at runtime, when a method exists in both a base class and a derived class, is based on the concrete type of the object which the method is called against, not the declared type of the variable which holds the reference to the object. Your first MyMethod is in an abstract class. So it can never be called from an object of type MyClass - because no such object can ever exist. All you can instanitate is derived class MySubClass. The concrete type is MySubClass, so that implementation is called, no matter that the code that calls it is in the base class.

    For non-virtual members/methods, just the opposite is true.

提交回复
热议问题