为什么C#允许没有抽象成员的抽象类? [英] Why does C# allow abstract class with no abstract members?

查看:305
本文介绍了为什么C#允许没有抽象成员的抽象类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C#的规范,节10.1.1.1 指出:

这是抽象类是允许的(但不是必需的
)包含抽象的
的成员。

An abstract class is permitted (but not required) to contain abstract members.

这让我可以创建类是这样的:

This allows me to create classes like this:

public abstract class A
{
    public void Main() 
    {
        // it's full of logic!
    }
}



甚至更好:

Or even better:

public abstract class A
{
    public virtual void Main() { }
}

public abstract class B : A
{
    public override sealed void Main()
    {
        // it's full of logic!
    }
}

这是一个真正的具体类;一心不能实例化它,它只是在目前为止的抽象。例如,如果我想在执行逻辑B.Main()我必须首先获得B的情况下,这是不可能的。

This is really a concrete class; it's only abstract in so far as one can't instantiate it. For example, if I wanted to execute the logic in B.Main() I would have to first get an instance of B, which is impossible.

如果传承人实际上并没有提供实现,那么,为什么把它叫做抽象?

If inheritors don't actually have to provide implementation, then why call it abstract?

换句话说,为什么C#允许只用混凝土构件的抽象类?

Put another way, why does C# allow an abstract class with only concrete members?

我要指出,我已经熟悉的抽象类型和成员的预期功能。

I should mention that I am already familiar with the intended functionality of abstract types and members.

推荐答案

也许一个很好的例子,是一种常见的基类,提供共享的特性,也许还有其他成员派生类,但并不代表一个具体的对象。例如:

Perhaps a good example is a common base class that provides shared properties and perhaps other members for derived classes, but does not represent a concrete object. For example:

public abstract class Pet
{
    public string Name{get;set;}
}

public class Dog : Pet
{
    public void Bark(){ ... }
}

所有宠物都有名字,但宠物本身是一个抽象的概念。宠物的实例必须是狗或一些其它种类的动物

All pets have names, but a pet itself is an abstract concept. An instance of a pet must be a dog or some other kind of animal.

这里的差别在于不是提供应被实现覆盖的方法,该基类声明所有的宠物都至少由名称属性。

The difference here is that instead of providing a method that should be overridden by implementors, the base class declares that all pets are composed of at least a Name property.

这篇关于为什么C#允许没有抽象成员的抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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