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]
Either make the class non nested or consider using the DataContractSerializer instead.
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' and
ReadObject' instead Serialize
and Deserialize