C # binary serialization

I am trying to serialize and deserialize objects to / from a Byte array for network communication, I currently have an "ISerialize" interface. However, I thought that there should be a more reliable way to do this with reflection.

I looked back at this a bit using BinaryFormater, but I can't figure out if it will give me the control I need.

EDIT:

I would like to be able to decorate a class as follows: (Where fields can be of any type, if they are systemic, or also [Serializable])

[Serializable]
public class MyClass {

    [NonSerialized]
    SomeOtherClass _classFeild;

    [Position (0)]
    UInt16 _field1;

    [Position (14)]
    UInt32 _feild2;

    //..........
}

And they have the following functionality:

void Test () {
    MyObject = new MyClass ();
    Byte[] raw;
    raw  =  Serializer.Serialize (MyClass); // Results in _field1 at raw[0,1]
                                            //            _field2 at raw[14-18]

    MyClass Deserialized  = Serializer.Deserialize<MyClass> (raw); 
}

where all fields are replaced with / from the network order (bigendian)


, , , . , , Framework, ?

+3
4
+1

I think the project that I recently posted on github might just be a fight for you. I argue that this will be the fastest binary serializer, and it has zero overhead. Each property is directly represented by its binary value.

Check out: https://github.com/Toxantron/CGbR#binary-datacontract-serializer

Entering right now the attribute DataContract and DataMember

[DataContract]
public partial class Root
{
    [DataMember]
    public int Number { get; set; }

    [DataMember]
    public Partial[] Partials { get; set; }

    [DataMember]
    public IList<ulong> Numbers { get; set; }
}

and generator output

    public byte[] ToBytes(byte[] bytes, ref int index)
    {
        // Convert Number
        Buffer.BlockCopy(BitConverter.GetBytes(Number), 0, bytes, index, 4);;
        index += 4;
        // Convert Partials
        // Two bytes length information for each dimension
        Buffer.BlockCopy(BitConverter.GetBytes((ushort)(Partials == null ? 0 : Partials.Length)), 0, bytes, index, 2);
        index += 2;
        foreach(var value in Partials ?? Enumerable.Empty<Partial>())
        {
            value.ToBytes(bytes, ref index);
        }
        // Convert Numbers
        // Two bytes length information for each dimension
        Buffer.BlockCopy(BitConverter.GetBytes((ushort)(Numbers == null ? 0 : Numbers.Count)), 0, bytes, index, 2);
        index += 2;
        foreach(var value in Numbers ?? Enumerable.Empty<ulong>())
        {
            Buffer.BlockCopy(BitConverter.GetBytes(value), 0, bytes, index, 8);;
            index += 8;
        }
        return bytes;
    }
0
source

Source: https://habr.com/ru/post/1719681/


All Articles