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

c# – 为什么不能在迭代器上下文中使用unsafe关键字?

发布时间:2020-12-15 06:09:22 所属栏目:百科 来源:网络整理
导读:在看这个问题时,Jon在回答……’ How to read a text file reversly with iterator‘方面做得很好.并且有一个类似的问题,我在使用指针hocus pocus …’ .net is there a way to read a text file from bottom to top‘之前就已经关闭…. 现在我开始尝试使用
在看这个问题时,Jon在回答……’ How to read a text file reversly with iterator‘方面做得很好.并且有一个类似的问题,我在使用指针hocus pocus …’ .net is there a way to read a text file from bottom to top‘之前就已经关闭….

现在我开始尝试使用指针来解决这个问题,好吧,它看起来很粗糙和边缘粗糙……

public class ReadChar : IEnumerable<char>
{
    private Stream _strm = null;
    private string _str = string.Empty;
    public ReadChar(string s)
    {
        this._str = s;
    }
    public ReadChar(Stream strm)
    {
        this._strm = strm;
    }
    public IEnumerator<char> GetEnumerator()
    {
        if (this._strm != null && this._strm.CanRead && this._strm.CanSeek)
        {
            return ReverseReadStream();
        }
        if (this._str.Length > 0)
        {
            return ReverseRead();
        }
        return null;
    }

    private IEnumerator<char> ReverseReadStream()
    {
        long lIndex = this._strm.Length;
        while (lIndex != 0 && this._strm.Position != 0)
        {
            this._strm.Seek(lIndex--,SeekOrigin.End);
            int nByte = this._strm.ReadByte();
            yield return (char)nByte; 
        }
    }

    private IEnumerator<char> ReverseRead()
    {
        unsafe
        {
            fixed (char* beg = this._str)
            {
                char* p = beg + this._str.Length;
                while (p-- != beg)
                {
                    yield return *p;
                }
            }
        }
    }
    IEnumerator IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

但发现C#编译器无法使用此实现来处理这个问题,但是当C#编译器因错误CS1629而拒绝时会被破坏 – “不安全代码可能不会出现在迭代器中”

为什么会这样?

解决方法

Eric Lippert在这里有一篇关于这个主题的优秀博客文章: Iterator Blocks,Part Six: Why no unsafe code?

(编辑:李大同)

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

    推荐文章
      热点阅读