I have this code:
[DataContract] class MyData { private Int32 dato1; [DataMember] public Int32 Dato1 { get { return dato1; } set { dato1 = value; } } public MyData(Int32 dato1) { this.dato1 = dato1; } public MyData() { this.dato1 = 0; } } [DataContract] class MyCollection2 : List<MyData> { public MyCollection2() { } }
Then I try to serialize a single MyCollection2 object with:
MyCollection2 collec2 = new MyCollection2(); collec2.Add(new MyData(10)); DataContractSerializer ds = new DataContractSerializer(typeof(MyCollection2)); using (Stream s = File.Create(dialog.FileName)) { ds.WriteObject(s, collec2); }
Then I get the following exception:
InvalidDataContractException is an invalid collection type because it has a DataContractAttribute
However, if I use the following class (does not inherit directly from the list, it has a List element instead):
[DataContract] class MyCollection1 { [DataMember] public List<MyData> items; public MyCollection1() { items = new List<MyData>(); } }
Serialization works fine here. You know why?. Thank you very much.
cls71 source share