为什么XmlSerializer会抛出InvalidOperationException?

qst*_*ter 9 .net c# exception invalidoperationexception

    public void Save() {
          XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation));
          /*
          A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
          A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
          A first chance exception of type 'System.InvalidOperationException' occurred in System.Xml.dll
          */

          // ....
     }
Run Code Online (Sandbox Code Playgroud)

如果您需要,这是全班:

public class DatabaseInformation
{
    /* Create new database */
    public DatabaseInformation(string name) {
        mName = name;
        NeedsSaving = true;
        mFieldsInfo = new List<DatabaseField>();
    }

    /* Read from file */
    public static DatabaseInformation DeserializeFromFile(string xml_file_path)
    {
    XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation));
        TextReader r = new StreamReader(xml_file_path);
        DatabaseInformation ret = (DatabaseInformation)Serializer.Deserialize(r);
        r.Close();
        ret.NeedsSaving = false;
        return ret;
    }

    /* Save */
    public void Save() {
    XmlSerializer Serializer = new XmlSerializer(typeof(DatabaseInformation));
        if (!mNeedsSaving)
            return;

        TextWriter w = new StreamWriter(Path.Combine(Program.MainView.CommonDirectory.Get(), Name + ".xml"), false);
        Serializer.Serialize(w, this);
        w.Close();
        NeedsSaving = false;
    }

    private string mName;
    public string Name { get { return mName; } }

    private bool mNeedsSaving;
    public bool NeedsSaving { get { return mNeedsSaving; } set { mNeedsSaving = value; Program.MainView.UpdateTitle(value); } }

    private bool mHasId;
    public bool HasId { get { return mHasId; } }

    List<DatabaseField> mFieldsInfo;
}
Run Code Online (Sandbox Code Playgroud)

(PS:如果你有任何改进我的代码的提示可以随意分享,我是一个C#初学者)

And*_*zub 15

要序列化/反序列化您的类型,它需要具有无参数构造函数.点击这里:

类必须具有要由XmlSerializer序列化的默认构造函数.

  • 我的类型有无参数构造函数,我仍然有这个错误.事实证明原因是一个Uri类型的公共属性,它没有无参数构造函数.因此,除了您的类型之外,该类型的公共属性也必须具有无参数构造函数. (8认同)

qst*_*ter 6

哦..我不知道它有其他信息(不得不点击"查看详细信息......"),神秘解决了:

Message = SDB.DatabaseInformation无法序列化,因为它没有无参数构造函数.