[英]Encoding a long to a VLQ byte array and writing it to System.IO.BinaryWriter
[英]How to use System.IO.BinaryWriter in C# with array of template/generic type?
我想知道是否有任何方法可以在C#中使用System.IO.BinaryWriter編寫模板/泛型類型的數組?
例如,我在模板化結構中有一個緩沖區:
T[] buffer
T通常是bool或byte 。 這個想法是要有一些方法可以編寫以下每種類型:
public void WriteByte(System.IO.BinaryWriter writer, int sizeToWrite)
{
if (typeof(T) != typeof(byte)) Error.Happened("Struct is not of type byte.");
// Direct use does not work even when T is 'byte'
writer.Write(buffer[i], 0, sizeToWrite);
// Casting does not work
writer.Write((byte[])buffer[i], 0, sizeToWrite);
}
但是,似乎沒有辦法使用模板化數組進行寫入。
任何建議將非常歡迎!
我不太確定目的是什么,但是可能的解決方法是:
public static void WriteByte<T>(T[] data, Converter<T, byte[]> converter, string path)
{
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
using (BinaryWriter writer = new BinaryWriter(stream))
{
foreach (var x in data)
{
var bytes = converter(x);
foreach (var b in bytes)
{
writer.Write(b);
}
}
}
}
}
或更簡單
public static void WriteBytes<T>(T[] data, Converter<T, byte[]> converter, string path)
{
using (FileStream stream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None))
{
foreach (T x in data)
{
var buffer = converter(x);
stream.Write(buffer, 0, buffer.Length);
}
}
}
測試用例:
static void Main(string[] args)
{
byte[] data = { 1, 2, 3, 4, 5, 6, 7 };
WriteByte(data, (b) => new byte[] { b }, @"C:\Temp\MyBinary1.myb");
int[] intData = { 1, 2, 3, 4, 5, 6, 7 };
WriteByte(intData, BitConverter.GetBytes, @"C:\Temp\MyBinary2.myb");
long[] longData = { 1, 2, 3, 4, 5, 6, 7 };
WriteByte(longData, BitConverter.GetBytes, @"C:\Temp\MyBinary3.myb");
char[] charData = { '1', '2', '3', '4', '5', '6', '7' };
WriteByte(charData, BitConverter.GetBytes, @"C:\Temp\MyBinary4.myb");
string[] stringData = { "1", "2", "3", "4", "5", "6", "7" };
WriteByte(stringData, Encoding.Unicode.GetBytes, "C:\Temp\MyBinary5.myb");
}
編輯:
另一種方法可能是這樣的:
public static void WriteBytes3<T>(T[] data, Action<T> writer)
{
foreach (T x in data)
{
writer(x);
}
}
static void Main(string[] args)
{
using (FileStream stream = new FileStream(@"C:\Temp\MyBinary6.myb", FileMode.Create, FileAccess.Write, FileShare.None))
using (BinaryWriter writer = new BinaryWriter(stream))
{
WriteBytes3(intData, writer.Write);
}
}
for(int i = 0; i < sizeToWrite; ++i)
{
writer.Write((byte)buffer[i]);
}
或更有效
writer.Write(Array.ConvertAll(buffer, b => (byte)b), 0, sizeToWrite);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.