Last active
December 6, 2019 12:50
-
-
Save ArseniySavin/3c9cffe64ac2ca868ff87a9ee6ecdfd7 to your computer and use it in GitHub Desktop.
Binary serialize extension
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class BinaryModelSerialaizer | |
{ | |
BinaryFormatter _binaryFormatter; | |
public BinaryModelSerialaizer(BinaryFormatter binaryFormatter) | |
{ | |
_binaryFormatter = binaryFormatter; | |
} | |
public byte[] Serialize<T>(T obj) | |
{ | |
using (MemoryStream s = new MemoryStream()) | |
{ | |
_binaryFormatter.Serialize(s, obj); | |
return s.ToArray(); | |
} | |
} | |
public T Deserialize<T>(byte[] data) | |
{ | |
using (MemoryStream s = new MemoryStream(data)) | |
{ | |
_binaryFormatter.Binder = new BinarySerializationBinder(typeof(T)); | |
return (T)_binaryFormatter.Deserialize(s); | |
} | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
sealed class BinarySerializationBinder : SerializationBinder | |
{ | |
Type _type; | |
public BinarySerializationBinder(Type type) | |
{ | |
_type = type; | |
} | |
public override Type BindToType(string assemblyName, string typeName) | |
{ | |
return _type; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment