2014-10-26 48 views
0

我有一個方法從IEnumerable<byte>中讀取可變數量的字節,並在找到某個標誌時停止。Port BinaryReader to IEnumerator?

是否有一種簡單而有效的方法來修改BinaryReader並使該方法只讀取必需的字節數?

P.S.如果沒有選擇,它也可以是另一種類型的StreamReader

回答

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

+0

我希望能有一個較短的解決方案我不想用冗餘類來污染代碼庫。我想我會用ex。方法與本地私有類相反。感謝您的建議! – Shimmy 2014-10-27 03:13:48

+0

@Dmitry你的MyBinaryReader的實現不會被編譯。爲什麼?看起來一切都是正確的。我也輸入了缺失的使用。 – ppk 2016-01-04 21:21:41

+0

@ppk你會得到什麼編譯錯誤?哪裏? – Dmitry 2016-01-06 15:02:23