2016-08-24 54 views
3

我想使用數組初始值設定從另一個字節數組中構建一個字節數組,以及一些其他形成頭/尾的字節。基本上,我想要做這樣的事情:C# - 我可以使用數組初始值設定從另一個建立一個字節數組嗎?

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

GetBytes()以上是虛構的,很遺憾。

有沒有什麼好的/優雅的方式來做到這一點?我通過使用BinaryWriter將所有內容寫入MemoryStream,然後將其轉換爲MemoryStream.ToArray()的字節數組來解決此問題,但感覺有點笨拙。

+0

這很煩人,因爲我wan't關閉這個[作爲欺騙(http://stackoverflow.com/questions/4616371/insert-a- byte-array-into-another-byte-array-at-a-specific-position-with-c-sharp)......但是你的具體措詞使得它免疫於此....所以要回答你煩人的措辭:NO – musefan

回答

6

你可以得到是最接近:

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

這將是非常低效雖然。你會更好做這樣的事情:

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過,在適當情況下。)

然後調用它:

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

一個簡單的方法是打出來的各成零件,然後CONCAT他們

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

您可以創建一個新的集合,是一個List<byte>,但其具有增加了的字節整個陣列的Add過載:

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

然後,這允許您使用集合初始化爲這種類型提供一個單一的字節或字節的序列,其可以再回頭到一個數組,如果你需要一個數組:

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

我不知道你可以重寫添加,所以你可以初始化一個集合該死! –

+0

@ johnny5我沒有覆蓋它。我超載了它。巨大差距。添加是「密封」的,所以不能被覆蓋。 – Servy

+0

我的意思是超負荷,今天早上沒有喝咖啡 –

相關問題