[英]Using XmlSerializer on a class with anonymous methods
I want to serialize a class which uses an anonymous function in its implementation. 我想序列化在其实现中使用匿名函数的类。 The compiler is generating an inner class to implement the anonymous function.
编译器正在生成一个内部类以实现匿名功能。 The serializer fails with the error: "MyClass+<>c__DisplayClass2 is inaccessible due to its protection level. Only public types can be processed."
序列化器失败,并显示以下错误:“由于其保护级别,无法访问MyClass + <> c__DisplayClass2。只能处理公共类型。”
public class MyClass {
public doIt() {
int objective = 0;
return List<int> () { 1 }.Any(i => i == objective);
}
}
new XmlSerializer(typeof(MyClass)).Serialize(writer, myClass);
How do I serialize this class? 我如何序列化此类? Thanks.
谢谢。
I cannot reproduce this exception with C# 3.0 and .NET 3.5 SP1 -- which tool-set are you using? 我无法在C#3.0和.NET 3.5 SP1中重现此异常-您使用的是哪个工具集?
Note that the XmlSerializer
doesn't serialize methods; 请注意,
XmlSerializer
不会序列化方法。 only values and properties. 仅值和属性。 Are you using another serializer by chance?
您是否正在偶然使用另一个串行器? If so, place the
SerializableAttribute
on the class definition as follows. 如果是这样,请将
SerializableAttribute
放在类定义上,如下所示。
[Serializable]
public class MyClass{ ... }
Here is the code I used to try to reproduce your issue, which is semantically equivalent. 这是我用来尝试重现您的问题的代码,在语义上是等效的。
public class MyClass
{
public bool doIt()
{
int objective = 0;
return new List<int>() { 1 }.Any(i => i == objective);
}
}
static class Program
{
static void Main(string[] args)
{
new XmlSerializer(typeof(MyClass)).Serialize(new MemoryStream(), new MyClass());
}
}
Instead of returning a List, you should make a new class marked serializable and send that. 而不是返回列表,您应该创建一个标记为可序列化的新类并将其发送。
[Serializable]
class MyList : List<int>
{
}
如果您不希望序列化下来,请使用XMLIgnore
属性标记doIt方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.