问题
I have a class with countless members.
I want to use DataContract
serialization/deserialization and so the class has the [DataContract]
attribute. If I put the [DataMember]
attribute that works otherwise it doesn't.
Am I to put [DataMember]
on all of them? Isn't there a way to automatically set ALL of them as datamembers?
Thanks
--EDIT--
The solution in Set DataContract and DataMember Without All the Attributes is not working.
public Test()
{
if (false)
{
MyClass theclass = new MyClass();
var serializer = new DataContractSerializer(typeof(MyClass));
using (Stream fileStream = File.Open("aaa.bin", FileMode.Create))
{
XmlDictionaryWriter binaryDictionaryWriter = XmlDictionaryWriter.CreateBinaryWriter(fileStream);
serializer.WriteObject(binaryDictionaryWriter, theclass);
binaryDictionaryWriter.Flush();
}
}
else
{
MyClass theclass;
var serializer = new DataContractSerializer(typeof(MyClass));
using (Stream fileStream = File.Open("aaa.bin", FileMode.Open))
{
XmlDictionaryReaderQuotas xq = new XmlDictionaryReaderQuotas();
XmlDictionaryReader binaryDictionarReader = XmlDictionaryReader.CreateBinaryReader(fileStream, xq);
theclass = (MyClass)serializer.ReadObject(binaryDictionarReader);
}
}
}
}
[DataContract(IsReference = true)]
public class MyClass
{
// need a parameterless constructor for serialization
public MyClass()
{
MyDictionary = new Dictionary<string, string>() { { "AAA", "BBB" } , {"CCC", "DDD"} };
}
public Dictionary<string, string> MyDictionary { get; set; }<----no attribute
public int aaaa = 3;<----no attribute
}
来源:https://stackoverflow.com/questions/34391288/how-to-set-datamember-on-all-class-members