数据数组的自定义序列化

本文关键字:序列化 自定义 数组 数据 | 更新日期: 2023-09-27 18:18:42

我有一个问题:

    protected Test(SerializationInfo info, StreamingContext context)
    {         
        sx = info.GetUInt16("sizex");
        sy = info.GetUInt16("sizey");
        sz = info.GetUInt16("sizez");
        ushort[] tab = new ushort[sx * sy * sz];
        tab = info.GetValue("data", System.UInt16[sx * sy * sz]);
        Console.WriteLine("Deserializing constructor");
    }
    [SecurityPermissionAttribute(SecurityAction.Demand, SerializationFormatter = true)]
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        Console.WriteLine("Serializing...");
        info.AddValue("sizex", sx);
        info.AddValue("sizey", sy);
        info.AddValue("sizez", sz);           
        info.AddValue("data", tab);
    }

我得到一个编译时错误:'ushort'是一个'type',在给定的上下文中是无效的。我应该改变什么?

数据数组的自定义序列化

info。GetValue需要一个类型,所以不包括数组的大小,而是用typeof包装它。此外,ushort[] tab = new ushort[sx * sy * sz];是不必要的。

ushort[] tab = (ushort[])info.GetValue("data", typeof(ushort[]));

试试这个:

    protected Test(SerializationInfo info, StreamingContext context)
    {         
        sx = info.GetUInt16("sizex");
        sy = info.GetUInt16("sizey");
        sz = info.GetUInt16("sizez");
        ushort[] tab = new ushort[sx * sy * sz];
        tab = (ushort[])info.GetValue("data", tab.GetType());
        Console.WriteLine("Deserializing constructor");
    }