是否可以对结构进行序列化

Sha*_*pta 4 c# oop serialization struct

我可以struct直接序列化类型,因为它是一个值类型.

我已经在课堂上使用它,但想知道它是否可以单独使用结构.

例如

struct student
{
   name string; --string is a reference type
   age int;
   designation string; --string is a reference type
   salary double;
};

class foo
{
 foo(){
   student s;
   s.name = "example";

   serialize(s);
  }
}
Run Code Online (Sandbox Code Playgroud)

这个链接说 "我试过让我的struct实现ISerializable,但我无法实现所需的构造函数,因为这是一个结构而不是一个对象."

410*_*one 7

是的你可以.我刚刚使用以下代码执行此操作.

[Serializable]
public struct TestStruct
{
    public int Value1 { get; set; }
    public int Value2 { get; set; }
    public string Value3 { get; set; }
    public double Value4 { get; set; }
}

TestStruct s1 = new TestStruct();
s1.Value1 = 43265;
s1.Value2 = 2346;
s1.Value3 = "SE";

string serialized = jss.Serialize(s1);
s2 = jss.Deserialize<TestStruct>(serialized);
Console.WriteLine(serialized);
Console.WriteLine(s2.Value1 + " " + s2.Value2 + " " + s2.Value3 + " " + s2.Value4);
Run Code Online (Sandbox Code Playgroud)

它做了什么?正是它应该有,序列化反序列化struct.

输出:

{"Value1":43265,"Value2":2346,"Value3":"SE","Value4":5235.3}
43265 2346 SE 5235.3
Run Code Online (Sandbox Code Playgroud)

好笑的是,那是TestStruct 序列化反序列化从到/ JSON.

那么默认的构造函数呢?所有 struct对象都有一个默认构造函数,它是对象的基本属性之一struct,默认构造函数只负责将struct对象所需的内存清除为默认值.因此,serializer 已经知道有一个默认的构造函数,因此可以继续进行,就好像它是一个常规对象(它是).

笔记:

这个例子使用System.Web.Script.Serialization.JavaScriptSerializer.

这个例子假设中所有变量structARE 特性.如果他们不是,那么这个答案可能无效.它似乎对我而言fields代替了properties,但这不是最好的做法.您应该始终确保public所有对象中的变量都是properties.


Zal*_*mon -1

好的,我会让你更容易,我就是这样做的

[StructLayout(LayoutKind.Sequential, Pack = 1)]
public class IClockFingerprintTemplate
{
    public ushort Size;
    public ushort PIN;
    public byte FingerID;
    public byte Valid;
    [MarshalAs(UnmanagedType.ByValArray)]
    public byte[] Template;
}

    protected static byte[] RawSerialize(object item, Type anyType)
    {
        int structSize;
        byte[] bff;
        IntPtr ptr;

        structSize = ((IClockFingerprintTemplate)item).Size; 
        ptr = Marshal.AllocHGlobal(structSize);
        Marshal.StructureToPtr(item, ptr, true);
        bff = new byte[structSize];
        Marshal.Copy(ptr, bff, 0, 6);
        Array.Copy(((IClockFingerprintTemplate)item).Template, 0, bff, 6, structSize - 6);
        Marshal.FreeHGlobal(ptr);
    }
Run Code Online (Sandbox Code Playgroud)