【问题标题】:Convert structure to byte array in .NET在.NET中将结构转换为字节数组
【发布时间】:2009-08-17 16:21:23
【问题描述】:

我希望使用 My.Computer.FileSystem.WriteAllBytes 等将由固定长度字符串组成的结构写入文件。

我正在使用一个带有固定长度字符串的 VB6 项目,我已将其转换为 VB.Net。

    Structure Record
        <VBFixedString(22),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=22)> Public tim() As Char
        <VBFixedString(130),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=130)> Public des() As Char
        <VBFixedString(2),System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.ByValArray,SizeConst:=2)> Public crlf() As Char
    End Structure

仍然是 C# 编组的新手,但我如何将这个结构转换为字节数组以写入文件。有一些编组技巧还是我必须编写自定义方法?

【问题讨论】:

  • 附带说明,结构不是引用类型。这是一个值类型。
  • 标题已更改。我知道,但由于某种原因仍然写了参考。

标签: vb.net marshalling bytearray


【解决方案1】:

使用 .NET 框架提供的序列化机制:

Dim formatter As New BinaryFormatter
formatter.Serialize(outputFileStream, objectInstance)

您应该将&lt;Serializable()&gt; 属性添加到您的类型。

【讨论】:

  • @dnh828,要添加到@Mehrdad 的答案,还要确保您尝试转换的对象图中的所有类型都用 [Serializable] 属性装饰...
  • 如何将可序列化属性应用于这些固定长度的字符串?
  • 你不需要。只需将其应用于StructureChar 数组是可序列化的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
  • 2011-03-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多