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

查看:26
本文介绍了为什么 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.

这里的区别在于,基类没有提供应该由实现者覆盖的方法,而是声明所有宠物至少由一个 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天全站免登陆