gpt4 book ai didi

c# - C# 中的流实现

转载 作者:行者123 更新时间:2023-12-04 00:46:49 25 4
gpt4 key购买 nike

我必须做什么才能实现我自己的流,它使用自定义压缩例程,类似于,例如,GZipStream

我显然必须继承 Stream 类,但哪些方法应该由我实现,哪些方法可以保留其默认实现?

基本上来说,文档有一个特殊的部分,但也许有更好更简单的选择?

Notes to Implementers

When implementing a derived class of Stream, youmust provide implementations for the Read and Write methods. Theasynchronous methods BeginRead, EndRead, BeginWrite, and EndWrite areimplemented through the synchronous methods Read and Write. Similarly,your implementations of Read and Write will work correctly with theasynchronous methods. The default implementations of ReadByte andWriteByte create a new single-element byte array, and then call yourimplementations of Read and Write. When deriving from Stream, if youhave an internal byte buffer, it is strongly recommended that youoverride these methods to access your internal buffer forsubstantially better performance. You must also provideimplementations of CanRead, CanSeek, CanWrite, Flush, Length,Position, Seek, and SetLength.

Do not override the Close method, instead, put all of the Streamcleanup logic in the Dispose method. For more information, seeImplementing a Dispose Method.

最佳答案

必须覆盖的方法是抽象的。在您全部实现它们之前,它不会编译。但是,您可以抛出 NotSupportedException,例如,如果您为 CanSeek 返回 false,则 Seek() 允许抛出。同样,如果您的流是只读的(对于 CanWrite 报告 false),那么它可以从 Write 中抛出。

实际上,对于像这样的复杂情况,我希望您最终会覆盖大部分(非异步)API。

关于c# - C# 中的流实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8255370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com