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

查看:115
本文介绍了为什么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!
    }
}

甚至更好:

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.

此处的区别在于,基类声明提供了所有pet至少由Name属性组成.而不是提供实现者应重写的方法.

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天全站免登陆