开发者

packing fields of a class into a byte array in c#

I am trying to create a fast way to convert c# classes into byte array. I thought of serializing the class directly to a byte array using an example I found:

// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
   if(obj == null)
       return null;
   BinaryFormatter bf = new BinaryFormatter();
   MemoryStream ms = new MemoryStream();
   bf.Serialize(ms, obj);
   return ms.ToArray();
}

But the byte array I got contains some other information that are not related to the fields in the class. I guess it is also converting the Properties of the class.

Is there开发者_如何学Go a way to serialize only the fields of the class to a byte array?

Thanks


This is how I would serialize the fields of a class to a byte[]:

public byte[] ToByteArray()
{
    using(MemoryStream stream = new MemoryStream())
    using(BinaryWriter writer = new BinaryWriter(stream))
    {
        writer.Write(MyInt);
        writer.Write(MyLong);
        writer.Write(Encoding.UTF8.GetBytes(MyString));
        ...

        return stream.ToArray();
    }
}


The formatter does not serialize the properties. But it does add some meta data. (class full name etc.)

Instead of bf.Serialize(ms, obj); you can use a function inisde the object that will serialized only the fields

bf.Serialize(ms, field1);
bf.Serialize(ms, field2);


You can prevent member variables from being serialized by marking them with the NonSerialized attribute as follows:

[Serializable]
public class MyObject 
{
    public int n1;
    [NonSerialized] public int n2;
    public String str;
}

You can even do your own custom serialization for your class. You can read all the information about it at the MSDN Documentation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜