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

查看:166
本文介绍了抽象方法使用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 将有一个的方法,我可以调用。以上为接口的等效可能是:

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();
  }
}



所以,关键的部分是:

So, the key parts are:


  1. 摘要类必须被继承。

  2. 摘要方法必须在派生类中实现。

  3. 虚拟方法可以在重写派生类型。

  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天全站免登陆