c# - 如何使用 sizeof 保留易重构?
问题描述
我需要获取用于将它们写入字节数组的变量的大小。但是我希望保留简单的重构,所以使用类似的东西sizeof(int)
并不能真正削减它。
这是我现在拥有的简化版本:
public byte[] ToBytes()
{
int byteIndex = 0;
byte[] result = new byte[sizeof(byte) + sizeof(byte) + sizeof(long) + RawBytes.Count];
...
BitConverter.TryWriteBytes(new Span<byte>(result, byteIndex, sizeof(long)), TimeStamp)
byteIndex += sizeof(long);
...
return result;
}
whereTimeStamp
是long
类型的属性。
如果我想改变TimeStamp
变量的类型,我现在需要修改这段代码的三个部分。当我添加更多变量时,会更容易出错。
而且每个变量sizeof()
指的是哪个变量也不是很清楚。
有简单的解决方案吗?或者sizeof(typeof(TimeStamp))
我是否需要制定一种解决方法,例如编写我自己的 sizeof-method 并对每种类型进行重载或is
检查我要使用的每种类型?
虽然不是我的问题的答案,但@HansPassant 建议使用 aBinaryWriter
并写入 aMemoryStream
将解决手头的问题。
解决方案
我不明白你想要做什么。尽管如此,你会在下面找到一个通用的实现可能性。
public byte[] ToBytes<T>()
{
int instance_layout_bytes = typeof(T).IsValueType ?
Unsafe.Sizeof<T>() :
Marshal.ReadInt32(typeof(T).TypeHandle.Value, 4);
int byteIndex = 0;
byte[] result = new byte[instance_layout_bytes + RawBytes.Count];
...
BitConverter.TryWriteBytes(new Span<byte>(result, byteIndex, instance_layout_bytes), T)
byteIndex += instance_layout_bytes;
...
return result;
}```
Inspired by :
[Size of managed structures][1]
[sizeof][2]
[1]: https://stackoverflow.com/questions/2127707/size-of-managed-structures
[2]: https://docs.microsoft.com/fr-fr/dotnet/csharp/language-reference/operators/sizeof
推荐阅读
- python - 将文件复制到外部驱动器:目标目录路径无效
- html - 在 Bootstrap 中使用 d-flex 时如何获取他父母的 div 高度
- javascript - 为什么 new Date() 返回 GMT-0500(东部标准时间)?
- reactjs - 如何序列化反应树的状态?
- gcc - 为什么启用尾部优化时回溯可能不正确
- excel - 如果 COL A 的特定行中的值存在于 COL D 中,则返回 TRUE 或 FALSE
- python-xarray - 带有 GFS 数据的metpy.calc.dewpoint_from_relative_humidity:ValueError:操作数无法与形状一起广播(31,)(34,)
- php - PHP 数组迭代以展平所有可能的结果
- azure - Azure API 管理“重写 url” - 如何删除 URL 前缀
- python - Python Seleinum 查找特定类的 div,如果另一个 div 位于其中,则查找第三个 div 并复制其中的文本