简体   繁体   中英

Serialize derived read-only property

I am serializing a data type to XML, and an exception is thrown:

System.Runtime.Serialization.InvalidDataContractException

The German error message is:

Es ist keine "set"-Methode für die "DerivedProperty"-Eigenschaft im Typ "MyApp.Models.MyEntry" implementiert.

Roughly translated, it tells me that an error occurred during serialization, because my read-only property "DerivedProperty" has no "set" method. But I won't implement a set method, as it is a read-only property, MyEntry is a serialization-only model (no deserialization on the server), and possibly because I am quite stubborn and hate such bad "solutions".

How do I tell .NET that my property is read-only and/or my model is serialization-only, so the exception goes away? My code is:

[DataContract]
public class MyEntry {
    internal string Property = null;
    [DataMember]
    public bool DerivedProperty {
        get {
            return Property == null;
        }
    }
}

There is a discussion about this here:

Why are properties without a setter not serialized

In summary, it is a limitation of XmlSerializer, DataContractSerializer provides more flexibility.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM