抽象方法使用 vs 常规方法 [英] abstract method use vs regular methods

查看:40
本文介绍了抽象方法使用 vs 常规方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道两种约定之间的区别:

I would like to know the difference between two conventions:

  1. 使用抽象方法创建抽象基类稍后将在派生类上实现.
  2. 创建一个没有抽象方法的抽象基类
    但是后面会在派生类的层面添加相关的方法.

有什么区别?

推荐答案

与接口非常相似,抽象类旨在为您的类型表达一组已知操作.然而,与接口不同的是,抽象类允许您实现可由任何派生类型使用的公共/共享功能.例如:

Much like interfaces, abstract classes are designed to express a set of known operations for your types. Unlike interfaces however, abstract classes allow you to implement common/shared functionality that may be used by any derived type. E.g.:

public abstract class LoggerBase
{
  public abstract void Write(object item);

  protected virtual object FormatObject(object item)
  {
    return item;
  }
}

在上面这个非常基本的例子中,我基本上做了两件事:

In this really basic example above, I've essentially done two things:

  1. 定义了我的派生类型将遵守的协定.
  2. 提供一些可以在需要时覆盖的默认功能.

鉴于我知道 LoggerBase 的任何派生类型都有一个 Write 方法,我可以调用它.上面作为接口的等价物可以是:

Given that I know that any derived type of LoggerBase will have a Write method, I can call that. The equivalent of the above as an interface could be:

public interface ILogger
{
  void Write(object item);
}

作为一个抽象类,我可以提供一个额外的服务FormatObject,它可以选择性地被覆盖,比如我正在编写一个ConsoleLogger,例如:

As an abstract class, I can provide an additional service FormatObject which can optionally be overriden, say if I was writing a ConsoleLogger, e.g.:

public class ConsoleLogger : LoggerBase
{
  public override void Write(object item)
  {
    Console.WriteLine(FormatObject(item));
  }
}

通过将 FormatObject 方法标记为虚拟,这意味着我可以提供一个共享的实现.我也可以覆盖它:

By marking the FormatObject method as virtual, it means I can provide a shared implementation. I can also override it:

public class ConsoleLogger : LoggerBase
{
  public override void Write(object item)
  {
    Console.WriteLine(FormatObject(item));
  }

  protected override object FormatObject(object item)
  {
    return item.ToString().ToUpper();
  }
}

所以,关键部分是:

  1. abstract 类必须被继承.
  2. abstract 方法必须在派生类型中实现.
  3. virtual 方法可以在派生类型中被覆盖.
  1. abstract classes must be inherited.
  2. abstract methods must be implemented in derived types.
  3. virtual methods can be overriden in derived types.

在第二种情况下,因为您不会向抽象基类添加功能,所以在直接处理基类的实例时无法调用该方法.例如,如果我实现了 ConsoleLogger.WriteSomethingElse,我就不能从 LoggerBase.WriteSomethingElse 调用它.

In the second scenario, because you wouldn't be adding the functionality to the abstract base class, you couldn't call that method when dealing with an instance of the base class directly. E.g., if I implemented ConsoleLogger.WriteSomethingElse, I couldn't call it from LoggerBase.WriteSomethingElse.

这篇关于抽象方法使用 vs 常规方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆