首页 > 解决方案 > 如何使用 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;
}

whereTimeStamplong类型的属性。

如果我想改变TimeStamp变量的类型,我现在需要修改这段代码的三个部分。当我添加更多变量时,会更容易出错。
而且每个变量sizeof()指的是哪个变量也不是很清楚。

有简单的解决方案吗?或者sizeof(typeof(TimeStamp))
我是否需要制定一种解决方法,例如编写我自己的 sizeof-method 并对每种类型进行重载或is检查我要使用的每种类型?

虽然不是我的问题的答案,但@HansPassant 建议使用 aBinaryWriter并写入 aMemoryStream将解决手头的问题。

标签: c#

解决方案


我不明白你想要做什么。尽管如此,你会在下面找到一个通用的实现可能性。

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

推荐阅读