Serialize to XML - private properties

前端 未结 2 485
攒了一身酷
攒了一身酷 2021-01-06 08:34

I\'m looking for a way to serialize a POCO that contains some read-only properties. In some Google and StackOverflow searches, I\'ve seen the following suggestions:

2条回答
  •  生来不讨喜
    2021-01-06 09:15

    Well, normally XmlSerializer can't serialize read-only properties... however there is a possibility to serialize properties with an internal set : you need to generate the XML serialization assembly, and declare it as a "friend" assembly using the InternalsVisibleTo attribute. You can automate this by adding the following code to your project file :

      
        
          
        
      
    

    And in AssemblyInfo.cs :

    [assembly: InternalsVisibleTo("MyAssembly.XmlSerializers")]
    

    Of course, you might not want the properties to have an internal set, but if you do, the solution above should work.

提交回复
热议问题