Remove [Serializable] attribute before class

Deadly 提交于 2020-01-15 06:22:05

问题


When working with the XmlSerializer, it is important that you mark your types with the [Serializable] attribute, part of the SerializableAttribute class.

class Program
{
    static void Main(string[] args)
    {
        XmlSerializer serializer = new XmlSerializer(typeof(Person));
        string xml;
        using (StringWriter stringWriter = new StringWriter())
        {
            Person p = new Person
            {
                FirstName = "John",
                LastName = "Doe",
                Age = 42
            };
            serializer.Serialize(stringWriter, p);
            xml = stringWriter.ToString();
        }
        Console.WriteLine(xml);
        using (StringReader stringReader = new StringReader(xml))
        {
            Person p = (Person)serializer.Deserialize(stringReader);
            Console.WriteLine("{0} {1} is {2} years old", p.FirstName, p.LastName, p.Age);
        }
        Console.ReadLine();
    }
}
[Serializable]
public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int Age { get; set; }
}

As you can see, the Person class is marked with Serializable. All members of the type are automatically serialized if they don't opt out.

However if I remove the Serializable attribute, the result is still same with it.

See the image.

Why? Serializable attribute is useless?


回答1:


When working with the XmlSerializer, it is important that you mark your types with the [Serializable] attribut

That is not correct. Only some serializers rely on that attribute, but not XmlSerializer.

Note that there are a number of inconsistencies between the various serializers in the .NET framework. Some will call a default constructor/execute field initializers, some will not. Some will serialize private members, some will not. Some use SerializableAttribute, some do not.

How does WCF deserialization instantiate objects without calling a constructor?

Read up on the specifics of the serializer you are using to avoid surprises.



来源:https://stackoverflow.com/questions/28031672/remove-serializable-attribute-before-class

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!