简体   繁体   English

为什么TextWriter.Write(char)不是抽象的?

[英]Why is TextWriter.Write(char) not abstract?

TextWriter is an abstract class with one abstract function - Encoding Encoding { get; } TextWriter是具有一个抽象功能的抽象类- Encoding Encoding { get; } Encoding Encoding { get; } . Encoding Encoding { get; } Implementations must also implement void Write(char) , but this function is not abstract - why? 实现也必须实现void Write(char) ,但是此函数不是抽象的-为什么? The default implementation does nothing which for me does not make sense. 默认实现对我来说没有任何意义。

It's a design error in TextWriter . 这是TextWriter的设计错误。 According to Reflector, all other Write* methods reduce to Write(char) . 根据Reflector的说法,所有其他Write*方法都简化为Write(char) The documentation says something similar. 该文件说类似。 Write(char) should be abstract. Write(char)应该是抽象的。

A developer not noticing this might be mislead to create an implementation that mostly works, but when writing a char (which is uncommon) it might do nothing. 如果开发人员没有注意到这一点,可能会误导其创建一个大多数情况下都可以实现的实现,但是在编写一个char (不常见)时,它可能什么都不做。 Surprising behavior. 令人惊讶的行为。

If you derive from TextWriter and you know that callers will only use certain overloads such as Write(string) you can save some work by only overriding the necessary methods and ignoring Write(char) . 如果您从TextWriter派生,并且知道调用方将仅使用某些重载,例如Write(string) ,则可以通过仅重写必要的方法并忽略Write(char)来节省一些工作。 That, however, violates the Liskov substitution principle. 但是,这违反了Liskov替代原则。 Back when the BCL was designed they might not have taken a strict stance on the SOLID principles. 早在设计BCL时,他们可能就没有对SOLID原则采取严格的立场。

The reference source is not enlightening: 参考资料没有启发性:

    // Writes a character to the text stream. This default method is empty,
    // but descendant classes can override the method to provide the
    // appropriate functionality.
    //
    public virtual void Write(char value) {
    }

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

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