简体   繁体   English

非抽象类中的抽象方法反之亦然

[英]Abstract methods in Non-abstract classes vice versa

What is the purpose of defining non-abstract methods in abstract classes and abstract methods in non-abstract classes? 在非抽象类中抽象类和抽象方法中定义非抽象方法的目的是什么?

What where the useful scenarios for using these? 使用这些的有用场景是什么?

  1. You cannot declare abstract method in non-abstract class. 您不能在非抽象类中声明abstract方法。 From C# spec: 来自C#规范:

    10.6.6 Abstract methods 10.6.6抽象方法

    (...) Abstract method declarations are only permitted in abstract classes (§10.1.1.1). (...)抽象方法声明仅允许在抽象类(第10.1.1.1节)中使用。

  2. Non-abstract method in abstract class is a method that do not have to (or sometimes even can't) be reimplemented in derived classes. abstract类中的非抽象方法是一种不必(或有时甚至不能)在派生类中重新实现的方法。

    They provide some implementation which is independent and the same across all derived classes (when don't mark as virtual ) or which can be overridden, but has some default behavior (with virtual modifier). 它们提供了一些在所有派生类中独立且相同的实现(当不标记为virtual )或者可以被覆盖但具有一些默认行为(使用virtual修饰符)。

    That's mainly how abstract classes differ from interfaces (which cannot contain any implementations). 这主要是抽象类与接口(不能包含任何实现)的不同之处。

One feature of abstract classes is that you can have implemented base class functionality in addition to abstract methods that must be implemented. 抽象类的一个特性是除了必须实现的抽象方法之外,您还可以实现基类功能。 This can be beneficial for code reuse. 这对于代码重用是有益的。

There can not be abstract methods in non abstract classes. 非抽象类中不能有抽象方法。

What is the purpose of defining non-abstract methods in abstract classes? 在抽象类中定义非抽象方法的目的是什么?

An abstract class declaring nothing but abstract methods is little different than declaring an interface; 一个抽象类只声明抽象方法与声明一个接口没什么不同; generally, an abstract class includes some minimum/default implementation-independent functionality while leaving abstract stubs for things that are implementation-dependent. 通常,抽象类包括一些最小/默认的与实现无关的功能,同时为依赖于实现的事物留下抽象存根。

...and abstract methods in non-abstract classes? ...和非抽象类中的抽象方法?

You cannot declare abstract methods in a non-abstract class. 您不能在非抽象类中声明抽象方法。

在这种情况下,将您的方法定义为Virtual而不是Abstract。

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

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