c#打开变量类型

Gar*_*thD 1 c# types type-conversion bitconverter

有可行的方法吗?给定一个字节流将其转换为所需的数字类型.

(假设调用代码将处理与流中的字节数相关的数据类型).

    public void GetValue(byte[] bytes, ref UInt16 value)
    {
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes);
        value = BitConverter.ToUInt16(bytes, 0);
    }
    public void GetValue(byte[] bytes, ref UInt32 value)
    {
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes);
        value = BitConverter.ToUInt32(bytes, 0);
    }
    public void GetValue(byte[] bytes, ref UInt64 value)
    {
        if (BitConverter.IsLittleEndian)
            Array.Reverse(bytes);
        value = BitConverter.ToUInt64(bytes, 0);
    }
    etc...
Run Code Online (Sandbox Code Playgroud)

我想有一个更好的方法,例如,通过切换值的类型,而不是复制的重载.

Jon*_*eet 6

那么你可以提取数组反转的条件,我根本不会使用重载:

public ushort GetUInt16(byte[] bytes)
{
    ReverseIfLittleEndian(bytes);
    return BitConverter.ToUInt16(bytes, 0);
}

public uint GetUInt32(byte[] bytes)
{
    ReverseIfLittleEndian(bytes);
    return BitConverter.ToUInt32(bytes, 0);
}

public ulong GetUInt64(byte[] bytes)
{
    ReverseIfLittleEndian(bytes);
    return BitConverter.ToUInt64(bytes, 0);
}

private static void ReverseIfLittleEndian(byte[] bytes)
{
    if (BitConverter.IsLittleEndian)
    {
        Array.Reverse(bytes);
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你真的想要一个单一的方法,我会避免尝试"可爱"并坚持"简单和可读".是的,您最终得到了几种类似的方法 - 但每种方法都很容易理解,调用简单,基本上没有维护.听起来不错...