简体   繁体   English

C# - 我可以使用数组初始化程序构建一个字节数组吗?

[英]C# - Can I use an array initializer to build one byte array out of another?

I'd like to use an array initializer to build one byte array out of another byte array as well as some other bytes that form a header/trailer. 我想使用数组初始化程序从另一个字节数组中构建一个字节数组,以及构成标题/尾部的其他一些字节。 Basically, I'd like to do something like this: 基本上,我想做这样的事情:

byte[] DecorateByteArray(byte[] payload)
{
    return new byte[] { 0, 1, 2, payload.GetBytes(), 3, 4, 5};
}

GetBytes() above is fictional, unfortunately. 不幸的是,上面的GetBytes()是虚构的。

Is there any nice/elegant way to do this? 这有什么好的/优雅的方式吗? I solved this by using a BinaryWriter to write everything to a MemoryStream , and then converting this into a byte array with MemoryStream.ToArray() , but it feels kind of clunky. 我通过使用BinaryWriter将所有内容写入MemoryStream ,然后使用MemoryStream.ToArray()将其转换为字节数组来解决这个问题,但它感觉有点笨重。

The closest you could get would be: 你可以得到的最接近的是:

byte[] DecorateByteArray(byte[] payload) =>
    new byte[] { 0, 1, 2 } 
       .Concat(payload)
       .Concat(new byte[] { 3, 4, 5 })
       .ToArray();

That would be pretty inefficient though. 那将是非常低效的。 You'd be better off doing something like: 你最好做以下事情:

static T[] ConcatArrays<T>(params T[][] arrays)
{
    int length = arrays.Sum(a => a.Length);
    T[] ret = new T[length];
    int offset = 0;
    foreach (T[] array in arrays)
    {
        Array.Copy(array, 0, ret, offset, array.Length);
        offset += array.Length;
    }
    return ret;
}

(Consider using Buffer.BlockCopy too, where appropriate.) (在适当的情况下,也考虑使用Buffer.BlockCopy 。)

Then call it with: 然后用:

var array = ConcatArrays(new byte[] { 0, 1, 2 }, payload, new byte[] { 3, 4, 5 });

You can create a new collection that is a List<byte> , but that has an overload of Add that adds a whole array of bytes: 您可以创建一个List<byte>的新集合,但是具有Add的重载,它会添加整个字节数组:

public class ByteCollection: List<byte>
{
    public void Add(IEnumerable<byte> bytes)
    {
        AddRange(bytes);
    }
}

This then lets you use the collection initializer for this type to supply either a single byte or a sequence of bytes, which you can then turn back into an array if you need an array: 然后,您可以使用此类型的集合初始值设定项来提供单个字节或字节序列,如果需要数组,则可以将其转换为数组:

byte[] DecorateByteArray(byte[] payload)
{
    return new ByteCollection() { 0, 1, 2, payload, 3, 4, 5 }.ToArray();
}

One easy way is to break out each into parts and then concat them 一种简单的方法是将每个部分分成几部分,然后将它们连接起来

byte[] DecorateByteArray(byte[] payload)
{  
    return new byte[] { 0, 1, 2}
        .Concat(payload.GetBytes())
        .Concat(new byte[] { 3, 4, 5});
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM