【问题标题】:c# switch on variable typec# 开启变量类型
【发布时间】:2015-06-21 17:19:42
【问题描述】:

有没有更可爱的方法来做到这一点? 给定一个字节流,将其转换为所需的数字类型。

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

    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...

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

【问题讨论】:

  • 我会开始让方法返回一个值并去掉ref参数...然后将方法命名为GetInt32等。使用@987654325 @ 参数只是为了让你可以重载方法对我来说感觉很糟糕。
  • 哦,你可能想看看pobox.com/~skeet/csharp/miscutil,其中包括EndianBitConverter...

标签: c# types type-conversion bitconverter


【解决方案1】:

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

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);
    }
}

如果您真的打算使用单一方法,我会避免尝试变得“可爱”并坚持“简单易读”。是的,您最终会得到几种类似的方法 - 但每种方法都易于理解、易于调用,并且基本上是零维护。对我来说听起来不错...

【讨论】:

    猜你喜欢
    • 2017-09-22
    • 2014-04-20
    • 1970-01-01
    • 2015-10-23
    • 2016-08-30
    • 2010-12-30
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    相关资源
    最近更新 更多