简体   繁体   中英

Obj->Bin in C#?

I am wondering if there is anything that can quickly convert my class into a byte[] . For example if i have class Foo { public string name; public int age } class Foo { public string name; public int age } I don't want to use reflection but still have a serialize without handwriting one.

The closest thing I know is dapper.net which generates IL code on the fly (after using reflection) and caches the IL/jit code so its pretty much full speed. It would be nice if i have an option to use a light/quick optional compressor for the string but not required. I may also want to throw Foo[] (or List<Foo> ) at this thing. What are my options?

Most anything that does serialization is going to use reflection. That doesn't mean it will be slow... often times it will cache the results of the initial calls to the reflection API. However, if (and only if) actual performance testing shows that the BinaryFormatter is not good enough for you, you might also try protobuf-net .

You can use the BinaryFormatter . Just serialize into a MemoryStream and then get the bytes.

You will have to sprinkle [Serializable] on the classes.

As an extension it would look like:

public byte[] ToByteArray(this object o)
{
    using (var s = new MemoryStream())
    {
       new BinaryFormatter().Serialize(s, o);
       return s.ToArray();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM