【发布时间】:2021-03-23 16:09:10
【问题描述】:
免责声明 - 由于我有一个可行的解决方案,这个问题可能会越过代码审查的界限,但我确信我正在重新发明轮子并且存在更好的解决方案。
上下文
我正在使用一个低级通信协议,通过该协议我收到一个byte[] 作为已知类型的序列化数组。数据类型将始终为 unmanaged 值类型,通常为 UInt16、char 等。
问题
我如何(应该)将byte[] 一般转换为T[],以免为每种情况提供实现,或键入特定的转换器?
工作代码
我在byte[]上写了一个扩展方法ToArray<T>:
public static T[] ToArray<T>(this byte[] input)
where T: unmanaged
{
// Use Reflection to find the appropiate MethodInfo from BitConverter
var converterMethod = (from method in typeof(BitConverter).GetMethods()
// Double redundant selection
where ((method.ReturnType == typeof(T)) && (method.Name == $"To{typeof(T).Name}"))
select method).FirstOrDefault();
// Create a Function delegate from the MethodInfo, since all BitConverter.To methods share a signiture
var converter = converterMethod.CreateDelegate(typeof(Func<byte[], int, T>));
// Some meta variables regarding the target type
int typeSize = Marshal.SizeOf<T>();
int count = input.Length / typeSize;
// Error Checking - Not yet implmented
if (input.Length % typeSize != 0) throw new Exception();
// Resulting array generation
T[] result = new T[count];
for(int i = 0; i < count; i++)
{
result[i] = (T)converter.DynamicInvoke(
input.Slice(i * typeSize, typeSize), 0);
}
return result;
}
这也取决于T[] 上的另一个小扩展Slice<T>:
public static T[] Slice<T>(this T[] array, int index, int count)
{
T[] result = new T[count];
for (int i = 0; i < count; i++) result[i] = array[index + i];
return result;
}
测试用例
class Program
{
static void Main(string[] args)
{
byte[] test = new byte[6]
{
0b_0001_0000, 0b_0010_0111, // 10,000 in Little Endian
0b_0010_0000, 0b_0100_1110, // 20,000 in Little Endian
0b_0011_0000, 0b_0111_0101, // 30,000 in Little Endian
};
UInt16[] results = test.ToArray<UInt16>();
foreach (UInt16 result in results) Console.WriteLine(result);
}
}
输出
10000
20000
30000
【问题讨论】:
-
你真的需要一个数组吗?您可以使用 2 行中的 span 来执行此操作,并且需要零分配/复制 - 您可以在 blittable span 类型之间进行强制转换。内存(跨度源)需要一点工作,但不多。
-
@MarcGravell 你好,谢谢。我以前没有遇到过跨度,现在简单看一下,我看到它们是如何替换我的
Slice扩展的。恐怕我看不到他们将如何提供通用转换? -
见下方答案
标签: c# generics type-conversion bitconverter