Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
390 views
in Technique[技术] by (71.8m points)

c# - Abstract class calling an abstract method

Can anyone explain to me why this works the way it does. The output comes out to "Print This". But how does the base class call bar(), when there is no implementation.

abstract class Base
{
    protected virtual void foo()
    {
        bar();
    }

    protected abstract void bar();
}

class Sub : Program
{
    protected override void foo()
    {
        base.foo();
    }

    protected override void bar()
    {
        Console.WriteLine("Print This");
    }

    static void Main(string[] args)
    {
        Sub obj = new Sub();

        obj.foo();
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

That's the whole point of an abstract class: that it will only ever exist concretely as an instance of the derived class(es). By declaring abstract methods or properties, it is simply forcing the derived class(es) to provide concrete implementations of those members. In this way, if you have an instance of type Base, you can call myInstance.bar and you know that the derived class has implemented it because it wouldn't compile otherwise.

By the way, use pascal case when naming methods, i.e. Foo and Bar.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...