【发布时间】: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