How to serialize non-static child class of static

2019-02-12 07:52发布

I want to serialize a pretty ordinary class, but the catch is it's nested in a static class like this:

public static class StaticClass
{
    [Serializable]
    public class SomeType
    {
        ...
    }
}

This code:

StaticClass.SomeType obj = new StaticClass.SomeType();
XmlSerializer mySerializer = new XmlSerializer(typeof(obj));

Produces this error:

StaticClass.SomeType cannot be serialized. Static types cannot be used as parameters or return types.

That error seems completely irrelevant; StaticClass.SomeType is not a static type.

Is there a way around this? Am I wrong to think this error is dumb?

3条回答
做自己的国王
2楼-- · 2019-02-12 08:32

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

查看更多
可以哭但决不认输i
3楼-- · 2019-02-12 08:50

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
    {
        ...
    }
}
查看更多
淡お忘
4楼-- · 2019-02-12 08:52

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

查看更多
登录 后发表回答