Je suis en train d'écrire du code pour faire de la sérialisation Xml. Avec, en dessous de la fonction.
public static string SerializeToXml(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
Si l'argument est une instance de la classe sans constructeur sans paramètre, il va lancer une exception.
Exception Non Gérée: Système.InvalidOperationException: CSharpConsole.Toto ne peut pas être sérialisé parce qu'il ne dispose pas d'un constructeur sans paramètre. au Système.Xml.La sérialisation.TypeDesc.CheckSupported() au Système.Xml.La sérialisation.TypeScope.GetTypeDesc(Type type, MemberInfo sourc e, Boolean directReference, Boolean throwOnError) au Système.Xml.La sérialisation.ModelScope.GetTypeModel(Type type Boolean Référence directe) à Système.Xml.La sérialisation.XmlReflectionImporter.ImportTypeMapping(Type type , attribut xmlrootattribute racine, Chaîne defaultNamespace) à Système.Xml.La sérialisation.XmlSerializer..ctor(Type type, String defaultName de l'espace) à Système.Xml.La sérialisation.XmlSerializer..ctor(Type type)
Pourquoi doit-il y avoir un constructeur sans paramètre, afin de permettre la sérialisation xml pour réussir?
EDIT: merci pour cfeduke de réponse. Le constructeur sans paramètre ne peut être privé ou interne.