How to get sub array without cloning

前端 未结 3 1201
借酒劲吻你
借酒劲吻你 2020-12-18 09:19

I know in C# we can always get the sub-array of a given array by using Array.Copy() method. However, this will consume more memory and processing time which is

3条回答
  •  清酒与你
    2020-12-18 09:46

    Assuming you have a Message wrapper class in C#? Why not just add a property on it called header that returns the top 20 bytes.

    You can easily accomplish this using skip and take suggested by Jonathon Reinhart above if you have the entire initial array in a memory array, but it sounds like you may have it in a network stream, which means the property might be a little more involved by doing a read of the initial 20 bytes from the the stream.

    Something along the lines of:

    class Message
    {
        private readonly Stream _stream;
        private byte[] _inMemoryBytes;
    
        public Message(Stream stream)
        {
            _stream = stream;
        }
    
        public IEnumerable Header
        {
            get
            {
                if (_inMemoryBytes.Length >= 20)
                    return _inMemoryBytes.Take(20);
    
                _stream.Read(_inMemoryBytes, 0, 20);
                return _inMemoryBytes.Take(20);
            }
        }
    
        public IEnumerable FullMessage
        {
            get
            {
                // Read and return the whole message. You might want amend to data already read.
            }
        }
    }
    

提交回复
热议问题