为什么抽象类有必要吗? [英] Why abstract classes necessary?

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

问题描述

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

1.什么是创建一个不能被实例化的类的地步?

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

最常见的是,作为一个基类或接口(一些语言有一个单独的接口结构,一些别'T) - 它不知道执行(即由子类来提供/实现类)

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。为什么会有人想要这样的类<? / p>

2.Why would anybody want such a class?

For abstraction and re-use

3.什么是在抽象类成为必要吗?任何人都可以用一个例子来介绍一下它的情况?

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