如何序列化静态类的非静态子类

ten*_*our 11 c# serialization static-classes

我想序列化一个非常普通的类,但问题是它嵌套在一个静态类中,如下所示:

public static class StaticClass
{
    [Serializable]
    public class SomeType
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

这段代码:

StaticClass.SomeType obj = new StaticClass.SomeType();
XmlSerializer mySerializer = new XmlSerializer(typeof(obj));
Run Code Online (Sandbox Code Playgroud)

产生此错误:

StaticClass.SomeType cannot be serialized. Static types cannot be used as parameters or return types.
Run Code Online (Sandbox Code Playgroud)

这个错误似乎完全无关紧要; StaticClass.SomeType不是静态类型.

有没有解决的办法?我错误地认为这个错误是愚蠢的吗?

Mar*_*ell 8

作为一种实用的解决方法 - 不要标记嵌套类型static:

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

    public class SomeType
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)