加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 18:01:23 所属栏目:百科 来源:网络整理
导读:我想序列化一个漂亮的普通类,但是catch是嵌套在这样的静态类中: public static class StaticClass{ [Serializable] public class SomeType { ... }} 这段代码: StaticClass.SomeType obj = new StaticClass.SomeType();XmlSerializer mySerializer = new X
我想序列化一个漂亮的普通类,但是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
    {
        ...
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读