C#-我可以使用数组初始值设定项从另一个数组构造一个字节数组吗? [英] C# - Can I use an array initializer to build one byte array out of another?

查看:62
本文介绍了C#-我可以使用数组初始值设定项从另一个数组构造一个字节数组吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用数组初始化程序从另一个字节数组以及构成头标/尾标的其他一些字节中构建一个字节数组。基本上,我想做这样的事情:

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()

有什么不错的/优雅的方法可以做到这一点吗?通过使用 BinaryWriter 将所有内容写入 MemoryStream ,然后使用 MemoryStream.ToArray(),但感觉有点笨拙。

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.

推荐答案

您能获得的最接近的是:

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;
}

(请考虑使用 Buffer.BlockCopy

(Consider using Buffer.BlockCopy too, where appropriate.)

然后用以下方式调用它:

Then call it with:

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

这篇关于C#-我可以使用数组初始值设定项从另一个数组构造一个字节数组吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆