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

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

问题描述

任何人都可以向我解释为什么它会这样工作.输出结果为 "Print This".但是基类如何调用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大小写,即FooBar.

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

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

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