2

在我的程序中,我有一个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));
    }
}
4

1 回答 1

2

使用接受 a 的通用方法Func

internal static byte[] ToBuffer<T>(SocketType type, Func<T, byte[]> getBytes, T value)
{
    byte[] packet = PacketTypeFactory.ToBuffer(type);
    byte[] valueBytes = 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;
}

并这样称呼它:

short shortValue = 5;
PacketFactory.ToBuffer(SocketType.Raw, BitConverter.GetBytes, shortValue);
// BitConverter.GetBytes(short)

int intValue = 10;
PacketFactory.ToBuffer(SocketType.Raw, BitConverter.GetBytes, intValue);
// BitConverter.GetBytes(int)

这样,正确的重载BitConverter.GetBytes将被传递给ToBuffer.

于 2017-03-11T17:47:59.207 回答