加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 将流转换为IEnumerable.如果可能的话,“保持懒惰”

发布时间:2020-12-15 06:18:36 所属栏目:百科 来源:网络整理
导读:我收到一个Stream,需要将IEnumerable传递给另一种方法. public static void streamPairSwitchCipher(Stream someStream){ ... someStreamAsIEnumerable = ... IEnumerable returned = anotherMethodWhichWantsAnIEnumerable(someStreamAsIEnumerable); ...}
我收到一个Stream,需要将IEnumerable传递给另一种方法.
public static void streamPairSwitchCipher(Stream someStream)
{
    ...
    someStreamAsIEnumerable = ...
    IEnumerable returned = anotherMethodWhichWantsAnIEnumerable(someStreamAsIEnumerable);
    ...
}

一种方法是读取整个流,将其转换为一个字节数组,并将其传递,因为Array实现了IEnumerable.但是如果我可以通过这样一种方式传递,那么在传入之前不必读取整个Stream就会更好一些.

public static IEnumerable<T> anotherMethodWhichWantsAnIEnumerable<T>(IEnumerable<T> p) {
    ... // Something uninteresting
}

解决方法

这个按字节’按需读取’字节读取您的流:
public static IEnumerable<byte> streamAsIEnumerable(Stream stream)
{
    if (stream == null)
        throw new ArgumentNullException("stream");

    for (; ; )
    {
        int readbyte = stream.ReadByte();
        if (readbyte == -1)
            yield break;
        yield return (byte)readbyte;
    }
}

或者甚至更短,如果流为空,但不会产生任何异常,则不会引发异常:

public static IEnumerable<byte> streamAsIEnumerable(Stream stream)
{
    if (stream != null)
        for (int i = stream.ReadByte(); i != -1; i = stream.ReadByte())
            yield return (byte)i;
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读