为什么需要抽象类? [英] Why abstract classes necessary?

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

问题描述

可能的重复:
什么是抽象类?

1.创建一个不能实例化的类有什么意义?

1.What is the point of creating a class that can't be instantiated?

最常用作基类或接口(有些语言有单独的接口构造,有些没有)——它不知道实现(由子类/实现类提供)

Most commonly to serve as a base-class or interface (some languages have a separate interface construct, some don't) - it doesn't know the implementation (that is to be provided by the subclasses / implementing classes)

2.为什么会有人想要这样的课程?

2.Why would anybody want such a class?

For abstraction and re-use

3.抽象类在什么情况下变成NECESSARY?谁能举个例子简单介绍一下?

3.What is the situation in which abstract classes become NECESSARY?can anyone brief it with an example?

推荐答案

抽象类并不总是必需,但它们通常很方便.假设我想为特定类型的文本文件编写一个解析器.

It isn't that abstract class are always necessary, but they're often quite convenient. Suppose I want to write a parser for a particular kind of text file.

// hasty code, might be written poorly
public abstract class FileParser<T> {
    private readonly List<T> _contents;
    public IEnumerable<T> Contents {
        get { return _contents.AsReadOnly(); }
    }

    protected FileParser() {
        _contents = new List<T>();
    }

    public void ReadFile(string path) {
        if (!File.Exists(path))
            return;

        using (var reader = new StreamReader(path)) {
            while (!reader.EndOfStream) {
                T value;
                if (TryParseLine(reader.ReadLine(), out value))
                    _contents.Add(value);
            }
        }
    }

    protected abstract bool TryParseLine(string text, out T value);
}

在将类似上面的东西放在一起之后,我已经完成了任何 FileParser-esque 类需要的样板代码.对于任何派生类,我需要做的只是覆盖一个抽象方法——TryParseLine——而不是编写处理流等的所有相同乏味的东西.此外,我可以轻松添加稍后的功能——例如异常处理——并将应用于所有派生类.

After throwing together something like the above, I've finished with the boilerplate code any FileParser-esque class would need. All I'd need to do for any derived class is simply override the one abstract method--TryParseLine--rather than write all the same tedious stuff dealing with streams, etc. Moreover, I could easily add functionality later--such as exception handling--and it will apply to all derived classes.

这篇关于为什么需要抽象类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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