问题
I have a class definition in separate assembly. The class is marked as serializable:
namespace example
{
[Serializable]
public class my_class
{
public List<string> text;
public FileStream audio;
public Image img;
public string nickname;
}
}
I can load this assembly and create an instance of this class with no problem. But when i try to cast to byte[] using code bellow
private byte[] ToByteArray()
{
if (send == null) // 'send' is a my_class instance;
return null;
BinaryFormatter bf = new BinaryFormatter();
bf.Binder = new Binder();
bf.AssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Full;
bf.Binder.BindToType(example_assembly.FullName, "my_class");
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, send);
return ms.ToArray();
}
i get:
System.Runtime.Serialization.SerializationException -> Type System.IO.FileStream in Assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
I don't understand this because whole class is marked as serializable. Any sugestions ??
回答1:
The Serializable
attribute simply indicates a class can be serialized. It does not change the underlying functionality of a class. You can mark non-serializable classes and members as serializable.
A FileStream
is not serializable. Marking it as such will not change that.
http://msdn.microsoft.com/en-us/library/system.serializableattribute(v=vs.110).aspx
回答2:
Members are serializable, but their types should also be serializable. FileStream is not. You can implement ISerializable interface in your class and manully serialize audio/img fields.
回答3:
The problem is that my_class
is decorated with the [SerializableAttribute]
, but the class FileStream is not. =/
You can skip the property serialization by decorating the FileStream property with a [NonSerializedAttribute]
, but you can't serialize a file Stream.
This is not very beautiful, but this guy here and here converted the stream to a string. You could control the serialization of your class by implementing the ISerializale interface and parse the FileStream to something that is Serializable.
来源:https://stackoverflow.com/questions/19918099/filestream-is-not-marked-as-serializable-but-the-whole-class-is