本文介绍了如何序列化静态类的非静态子类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想序列化一个非常普通的类,但要注意的是它嵌套在这样的静态类中:
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
{
...
}
}
此代码:
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
不是静态类型.
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?
推荐答案
作为一种实用的解决方法-不要标记嵌套类型static
:
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
{
...
}
}
这篇关于如何序列化静态类的非静态子类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!