How to serialize non-static child class of static class

时光毁灭记忆、已成空白 提交于 2019-11-30 18:09:02

As a pragmatic workaround - don't mark the nesting type static:

public class ContainerClass
{
    private ContainerClass() { // hide the public ctor
        throw new InvalidOperationException("no you don't");
    }

    public class SomeType
    {
        ...
    }
}

It's know limitation in XmlSerializer ()

And workaround is to use DataContractSerializer (DataContractAttribute + DataMemberAttribute)

var ser = new DataContractSerializer(typeof (StaticClass.SomeType));
var obj = new StaticClass.SomeType {Int = 2};
ser.WriteObject(stream, obj);

...

static class StaticClass
{
    [DataContract]
    public class SomeType
    {
        [DataMember]
        public int Int { get; set; }
    }
}

As you can see DataContractSerializer doesn't even require StaticClass to be public. One difference is that you should use WriteObject' andReadObject' instead Serialize and Deserialize

Either make the class non nested or consider using the DataContractSerializer instead.

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