开发者

Why does this.One() call the overrider method from class B and not the virtual one from class A?

开发者 https://www.devze.com 2023-03-11 21:40 出处:网络
class A { public virtual int one() { return 100; } public virtual int two() { return 200; } public virtual int three()
class A
{
    public virtual int one()
    {
        return 100;
    }

    public virtual int two()
    {
        return 200;
    }

    public virtual int three()
    {
        return this.one();
    }
}

class B : A
{ 
    public override int one()
    {
        return 300;
    }

    public override int two()
    {
        return this.one();
    }

    public override int three()
    {
        return开发者_开发问答 base.three();
    }
}
class Program
{
    static void Main(string[] args)
    {
        A b = new B();
        Console.WriteLine(b.three());
    }
}

Why does this code return "300"?


Because it's virtual.

The whole point of virtual methods is that you always call the overridden version.


That is the definition of an override.

The virtual keyword basically means, "Subclasses can override this method".

The override keyword basically means, "My base class has a virtual method that I am redefining"

I think your confusion is because the this.one() is called from the class A. But, the this still refers to an instance of the class B, which is why the method on B is called.


What @SLaks said.

But specifically, b.three() invokes B.three, which invokes A.three, which invokes B.one.


I think when you say return base.three(); in the overridden method you should acutaly be calling return this.three(); other wise you'll be accessing the base class which is A.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号