问题
BinaryFormatter works great, but doesn't exist in Portable class libraries for .NET 4.5.
I've read that it IS in .NET 4.6 Portable. I have not confirmed this because when I change to 4.6 in my project settings, I get a warning message that "4.5 will be automatically targeted" unless I de-select Silverlight, WindowsPhone, Windows Universal, Xamarin, etc), so I can only target .NET 4.6 Portable if I'm NOT targeting additional platforms, thus defeating the purpose.
Here is my original BinarySerializer (Works but NOT PCL because uses BinaryFormatter)
private string BinarySerialize(object Source)
{
byte[] serializedObject;
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, Source);
serializedObject = stream.ToArray();
}
return Convert.ToBase64String(serializedObject);
}
So, that being said, I started trying to re-write my BinarySerializer to use BinaryReader and BinaryWriter which are both available in PCL, and ran into the following issues:
BinaryWriter, can only handle simple types (like string, bool, byte, long, int, etc) and Streams, so think I need to find a way to convert anonymous objects to a Stream.
Am I on the right path? How do you convert types which are not known until runtime (like a System.Delegate - and yes I know serializing delegates produces brittle code) or anonymouse\generic types to their equivalent byte array byte[]? Is there a way to convert an object directly to a Stream or MemoryStream?
If this is not possible at all, how would you recommend I write an interface for my BinarySerializer, so I can implement the functionality in my portable class library while the actual BinaryFormatter classes implementing the interface exists in platform-specific assemblies?
FYI, this is an MVVM project in which "Serializers" are considered Models deriving from a ValueConverter abstract base class. Serialization is only used to transport instantiated tasks to their destination for execution.
来源:https://stackoverflow.com/questions/36315037/c-sharp-anonymous-generic-object-to-byte-without-binaryformatter-in-net-4