DataContractSerializer不会序列化受保护的属性

时间:2013-11-19 19:07:32

标签: c# .net xml-serialization datacontractserializer

我将类的公共属性更改为受保护的

public class SlideSet : UserModifiable.Properties, Validation.IValidateable
{
    public virtual ICollection<Slide> Slides { get; set; }

public class SlideSet : UserModifiable.Properties, Validation.IValidateable
{
    [DataMember]
    protected virtual ICollection<Slide> Slides { get; set; }

但现在DataContractSerializer不再将其序列化为xml。我的印象from the docsDataMember属性是唯一必要的工作。

这是我的序列化实现

    public string ToXml(Object obj) {
        // set up DataContractSerializer to use the .NET ProxyDataContractResolver, which helps us to serialize EF objects
        var entityType = ObjectContext.GetObjectType(obj.GetType());
        var knownTypes = ObjectContext.GetKnownProxyTypes();
        var resolver = new ProxyDataContractResolver();
        var serializer = new DataContractSerializer(entityType, entityType.Name, string.Empty, knownTypes, 1000, true, true, null, resolver);

        // serialize to XML string
        var stream = new MemoryStream();
        serializer.WriteObject(stream, obj);
        stream.Seek(0, SeekOrigin.Begin);
        return Encoding.UTF8.GetString(stream.ToArray());
    }

为什么我的受保护资产没有被序列化?

1 个答案:

答案 0 :(得分:1)

如果您希望使用DataContractSerializer正确序列化XML,则不仅需要在每个序列化属性上使用DataMemberAttribute,还需要在类本身上使用DataContractAttribute

这两个工作如文档中所述:

MSDN - DataContractSerializer