【问题标题】:Port BinaryReader to IEnumerator?端口 BinaryReader 到 IEnumerator?
【发布时间】:2014-10-26 22:44:21
【问题描述】:

我有一个方法可以从IEnumerable<byte> 读取可变数量的字节,并在找到某个标志时停止。

是否有一种简单有效的方法来调整BinaryReader 并使该方法只读取必要数量的字节?

附:如果别无选择,也可以是另一种类型的StreamReader

【问题讨论】:

    标签: c# .net binary ienumerable binaryreader


    【解决方案1】:

    如果我理解正确,您需要将BinaryReader 传递给期望IEnumerable<byte> 的方法。如果是这样,请尝试使用此类:

    public class MyBinaryReader : BinaryReader, IEnumerable<byte>
    {
        public MyBinaryReader(Stream input)
            : base(input)
        {
        }
    
        public MyBinaryReader(Stream input, Encoding encoding)
            : base(input, encoding)
        {
        }
    
        public IEnumerator<byte> GetEnumerator()
        {
            while (BaseStream.Position < BaseStream.Length)
                yield return ReadByte();
        }
    
        IEnumerator IEnumerable.GetEnumerator()
        {
            return GetEnumerator();
        }
    }
    

    使用示例:

    private static void ReadFew(IEnumerable<byte> list)
    {
        var iter = list.GetEnumerator();
        while (iter.MoveNext() && iter.Current != 3)
        {
        }
    }
    
    using (MemoryStream memStream = new MemoryStream(new byte[] { 0, 1, 2, 3, 4, 5 }))
    using (MyBinaryReader reader = new MyBinaryReader(memStream))
    {
        ReadFew(reader);
        Console.WriteLine("Reader stopped at position: " + memStream.Position);
    }
    

    输出:

    阅读器停在位置:4

    【讨论】:

    • 我希望有一个更短的解决方案,我不想用冗余类污染代码库。我想我会用ex。使用本地私有类的方法。感谢您的建议!
    • @Dmitry 您的 MyBinaryReader 实现无法编译。为什么 ?似乎一切都好。我也输入了缺少的 using's。
    • @Dmitry 错误是“无法实现'System.Collections.IEnumerable.GetEnumerator()',因为它没有'System.Collections.IEnumerator”的匹配返回类型。我的错是没有声明父命名空间 System.Collections。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    • 2012-05-08
    • 1970-01-01
    相关资源
    最近更新 更多