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 wi开发者_JAVA技巧th the error: "MyClass+<>c__DisplayClass2 is inaccessible due to its protection level. Only public types can be processed."
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?
Note that the XmlSerializer
doesn't serialize methods; only values and properties. Are you using another serializer by chance? If so, place the SerializableAttribute
on the class definition as follows.
[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>
{
}
Mark the doIt method with XMLIgnore
attribute, if you don't want that serialized down.
精彩评论