简体   繁体   English

C#:抽象类中的抽象和非抽象方法?

[英]C#: abstract and non-abstract methods in an abstract class?

I am not sure whether the code I'm writing makes sense. 我不确定我写的代码是否有意义。 Here's the general idea: 这是一般的想法:

I have a Parser class that will take different types of documents. 我有一个Parser类,它将采用不同类型的文档。 Depending on the type, I will parse the document differently. 根据类型,我将以不同方式解析文档。

So suppose I have two types of documents, A and B. The factory pattern seems like a pretty good way to go about doing this in case I need to extend the program to handle additional types, so I will have an abstract class. 因此,假设我有两种类型的文档,A和B.如果我需要扩展程序来处理其他类型,工厂模式似乎是一个非常好的方法,所以我将有一个抽象类。

abstract class Parser
{
   ...
   public void common_method() {
      // something common that all parsers will use
      // like file IO
   }

   // derived classes will override this
   public abstract void specific_method();
}

class A_Parser : Parser
{
   ...
}

class B_Parser : Parser
{
   ...
}

The issue I'm wondering about is the fact that I have declared abstract methods and non-abstract methods in my abstract Parser. 我想知道的问题是我在抽象的Parser中声明了抽象方法和非抽象方法。 Compiler doesn't seem to be complaining, and it still seems to work correctly. 编译器似乎没有抱怨,它似乎仍然正常工作。

Is this non-standard? 这不标准吗? Maybe there's a better way to design this? 也许有更好的方法来设计它?

This is perfectly fine. 这很好。 If you only had abstract methods, you'd have essentially an interface. 如果你只有抽象方法,那么你基本上就有一个接口。 You may have to use another pattern to create the actual instances of the parser if necessary, but as far as the class definition goes, this is pretty standard. 如果需要,您可能必须使用另一种模式来创建解析器的实际实例,但就类定义而言,这是非常标准的。

这非常好,您甚至可以制作一些非必须覆盖的virtual方法

This is the typical implementation of the Template Method Pattern . 这是模板方法模式的典型实现。 You provide the general pattern for algorithm but the details are implemented in concrete classes. 您提供算法的一般模式,但详细信息在具体类中实现。

It is common to have non abstract method in abstract class. 在抽象类中使用非抽象方法是很常见的。

You should also know that as your Parser class is abstract, the only way one can access common_method is via instance of A_Parser or B_Parser class. 您还应该知道,因为您的Parser类是抽象的,所以可以访问common_method的唯一方法是通过A_Parser或B_Parser类的实例。

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

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