简体   繁体   English

没有任何抽象方法的C#中的抽象类

[英]Abstract class in C# without any abstract method

Folks 民间

I am surprised to see my code working, that I dont have any abstract method in abstract class. 我很惊讶地看到我的代码有效,我在抽象类中没有任何抽象方法。 But as per rules we should have atleast one abstract method right ? 但是按照规则,我们应该至少有一种抽象方法吧? :S :S

No, you don't need an abstract method in an abstract class. 不,在抽象类中不需要抽象方法。

The restrictions are: 限制是:

  • If a class has an abstract method, property, index, or event then the class must also be abstract. 如果类具有抽象方法,属性,索引或事件,则该类也必须是抽象的。
  • You can't instantiate an abstract class. 您不能实例化一个抽象类。

There is no requirement that abstract classes must have abstract methods. 不需要抽象类必须具有抽象方法。

No, this is entirely valid. 不,这是完全有效的。 Indeed, every static class in C# is actually an abstract and sealed class in .NET. 实际上,C#中的每个static类实际上都是.NET中的抽象密封类。 (You can't declare an abstract class to be sealed with C# source code though.) (不过,您不能声明抽象类使用C#源代码密封。)

The C# 4 spec explicitly calls this out, in section 10.1.1.1 (abstract classes): C#4规范在10.1.1.1节(抽象类)中明确指出了这一点:

An abstract class is permitted (but not required) to contain abstract members. 允许(但不是必需)抽象类包含抽象成员。

It's certainly rare to have an abstract class with no abstract members, but it's not unheard of. 没有抽象成员的抽象类当然很罕见 ,但这并不是闻所未闻的。 (Don't forget that it's not just methods that can be abstract - you can have abstract events and properties, too.) (不要忘记,可以抽象的不仅是方法-您也可以具有抽象事件和属性。)

From MSDN - abstract (Emphasis added): MSDN-摘要 (已添加强调):

An abstract class may contain abstract methods and accessors. 抽象类可以包含抽象方法和访问器。

Your abstract class can contain nothing but non-abstract methods, or it could be am empty class if you want. 您的抽象类只能包含非抽象方法,或者可以是空类,如果需要的话。 It gives you a base class that cannot be instantiated, which could be useful for plymorphism. 它为您提供了无法实例化的基类,这对于多态性很有用。

You don't need abstract methods to have an abstract class. 您不需要抽象方法即可拥有抽象类。 Sometimes it's useful to just restrict a class from being instantiated, and designate it as a base to some inheritance hierarchy. 有时仅限制类的实例化,并将其指定为某些继承层次结构的基础是有用的。 All the methods can be defined in an abstract class. 可以在抽象类中定义所有方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM