gpt4 book ai didi

c# switch on 变量类型

转载 作者:太空宇宙 更新时间:2023-11-03 19:04:57 25 4
gpt4 key购买 nike

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

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

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

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

最佳答案

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

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

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

关于c# switch on 变量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29655446/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com