How to set [DataMember] on all class members

馋奶兔 提交于 2019-12-12 13:24:20

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!