Problems with BinaryFormatter on class with DataContract?
I have a class
[DataContract]
public class Car
{
public bool pbIsHatchBack;
string prSt = "royi";
}
And i want to serialize it with BinaryFormatter:
BinaryFormatter binFormat = new BinaryFormatter();
Stream fStream = new FileStream("c:\\CarData.dat", FileMode.Create, FileAccess.Write, FileShare.None);
binFormat.Serialize(fStream, carObj);
fStream.Close();
But u get this error
Type 'SerializationTypes+Car' in Assembly '开发者_开发百科ConsoleApplication2, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' is not marked as serializable.
If i remove the [DataContract] and replace it with [Serializable] its ok. but why ?
how WCF does it behind the scene (when tcpBinding ?)?
Why can't i use the DataContract ???
WCF does not use the BinaryFormatter
to serialize its objects, it uses either the DataContractSerializer
(by default) or some of its other serializers (XmlSerializer
, DataContractJsonSerializer
, etc). BinaryFormatter
was released before WCF (in .NET Framework 1.0, IIRC) so is not aware of the [DataContract]
/[DataMember]
attributes (which were released in .NET Framework 3.0, along with WCF.
On netTcpBinding
WCF still uses the DataContractSerializer
, but instead of using a "normal" XML reader/writer, it uses a binary-aware XML reader/writer, which is how we have the binary encoding in WCF.
The WCF serializers understand the [Serializable]
attribute, so you can use it with WCF as well. Or you can also use both attributes, if you want your type to be serializable by the BinaryFormatter
but use the more fine-grained control that the [DC]/[DM] attributes give you.
精彩评论