c# – 如何序列化静态类的非静态子类

前端之家收集整理的这篇文章主要介绍了c# – 如何序列化静态类的非静态子类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想序列化一个漂亮的普通类,但是catch是嵌套在这样的静态类中:
public static class StaticClass
{
    [Serializable]
    public class SomeType
    {
        ...
    }
}

这段代码

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

产生此错误

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

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

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

解决方法

作为务实的解决方法 – 不要将嵌套类型标记为static:
public class ContainerClass
{
    private ContainerClass() { // hide the public ctor
        throw new InvalidOperationException("no you don't");
    }

    public class SomeType
    {
        ...
    }
}

猜你在找的C#相关文章