在我的程序中,我有一个PacketFactory
构建缓冲区以准备通过NetworkStream
. 正如您在下面看到的,此方法采用一个短作为参数。这个短传给BitConverter.GetBytes
.
internal static class PacketFactory
{
internal static byte[] ToBuffer(PacketType type, short value)
{
byte[] packet = PacketTypeFactory.ToBuffer(type);
byte[] valueBytes = BitConverter.GetBytes(value);
byte[] buffer = new byte[packet.Length + valueBytes.Length];
Array.Copy(packet, 0, buffer, 0, packet.Length);
Array.Copy(valueBytes, 0, buffer, packet.Length, valueBytes.Length);
return buffer;
}
}
现在我的问题是: BitConverter.GetBytes
有 10 个重载。我想轻松地将所有这些重载用于方法value
中的参数ToBuffer
。
天真的解决方案:创建所有也存在的重载BitConverter.GetBytes
并将所有内容传递给内部方法。有没有更好的方法来解决这个问题?
internal static class PacketFactory
{
private static byte[] ToBuffer(PacketType type, byte[] value)
{
byte[] packet = PacketTypeFactory.ToBuffer(type);
byte[] buffer = new byte[packet.Length + value.Length];
Array.Copy(packet, 0, buffer, 0, packet.Length);
Array.Copy(value, 0, buffer, packet.Length, value.Length);
return buffer;
}
internal static byte[] ToBuffer(PacketType type, short value)
{
return ToBuffer(type, BitConverter.GetBytes(value));
}
internal static byte[] ToBuffer(PacketType type, int value)
{
return ToBuffer(type, BitConverter.GetBytes(value));
}
}