使用编组忽略类属性

时间:2016-12-21 08:24:45

标签: c# marshalling

我需要将此类的ObservableCollection导出为二进制文件:

[StructLayout(LayoutKind.Sequential)]
[XmlRoot("RxFrame")]
public class RxFrame : BaseClass
{
    [XmlAttribute]
    public string ID { get; set; } = "00000000";

    [XmlAttribute]
    public int IntVal{ get; set; } = 0;

    [XmlAttribute]
    public bool IsExtended { get; set; } = false;

    public RxFrame()
    {
    } 
}

这是将数据导出为二进制文件的函数:

[StructLayout(LayoutKind.Sequential)]
public class BaseClass
{
    public BaseClass()
    { }

    public virtual byte[] getBinaryData()
    {
        int size = Marshal.SizeOf(this);
        IntPtr ptr = Marshal.AllocHGlobal(size);
        byte[] buffer = new byte[Marshal.SizeOf(this)];
        Marshal.StructureToPtr(this, ptr, false);
        Marshal.Copy(ptr, buffer, 0, Marshal.SizeOf(this));
        Marshal.FreeHGlobal(ptr);
        return buffer;
    }
}

这是每个元素的循环:

using (FileStream mstream = File.Open(filePathParam + "RX.bin", FileMode.Create))
{
   BinaryWriter bWriter = new BinaryWriter(mstream, Encoding.UTF8);
   bWriter.Write(ListeRxFrames.Count);
   foreach (RxFrame rx in ListeRxFrames)
   {
       bWriter.Write(rx.getBinaryData());
   }
   bWriter.Close();
}

这很好用,但我只需要将RxFrame类的IntValIsExtended属性导出为二进制。我该怎么做?

1 个答案:

答案 0 :(得分:3)

编组对象时无法忽略字段。也许您需要为要编组的数据创建一个单独的类。