It is easy to convert primitive types to bytes by using Buffer.BlockCopy().
But if I have a array of DateTime, which function should I use to convert the DateTime[] to byte[]?
If I have a constant size of struct (which means I can use Marshal to convert struct to byte[]), which way should I use to convert the T[](struct array) to byte[]?
If you are after a copy of the underlying in-memory representation, then one approach is to just access the data unsafe
- something like:
// invent some data
DateTime[] original = new DateTime[10];
for (int i = 0; i < original.Length; i++)
original[i] = new DateTime(2014, 1, i + 1);
byte[] blob = new byte[original.Length * sizeof(DateTime)];
fixed (DateTime* src = original)
fixed (byte* dest = blob)
{
DateTime* typedDest = (DateTime*)dest;
for(int i = 0; i < original.Length; i++)
{
typedDest[i] = src[i];
}
}
However, this is hugely dependent upon what you expect the contents of the byte[]
to be afterwards, and what you intend doing with it.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.