调用抽象方法的抽象类 [英] Abstract class calling an abstract method

查看:117
本文介绍了调用抽象方法的抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以向我解释为什么这样做会起作用。输出结果为打印此 。但是,如果没有实现,基类如何调用 bar()

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();
    }
}


推荐答案

抽象类的全部要点:它将仅作为派生类的实例具体存在。通过声明抽象方法或属性,仅是在强制派生的类提供这些成员的具体实现。这样,如果您的实例类型为 Base ,则可以调用 myInstance.bar ,并且您知道

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.

顺便说一句,在命名方法时使用pascal大小写,即 Foo Bar

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

这篇关于调用抽象方法的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆