11
    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
          */

          // ....
     }

如果您需要,这是整个课程:

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;
}

(PS:如果您有任何改进我的代码的技巧,请随时分享,我是 C# 初学者)

4

4 回答 4

17

要序列化/反序列化您的类型,它需要有无参数构造函数。在这里查看:

一个类必须有一个默认构造函数才能被 XmlSerializer 序列化。

于 2010-03-23T07:36:31.670 回答
6

哦..我不知道它有其他信息(必须点击“查看详细信息..”),谜团解决了:

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

于 2010-03-23T07:37:00.630 回答
1

我也遇到了这个异常,但这不是因为缺少默认构造函数。我有一些额外的属性(aListDictionary),它们不是 XML 文档的一部分。

装饰这些属性[XmlIgnore]为我解决了这个问题。

于 2013-09-24T20:20:01.890 回答
0

您可以通过提供调用重载构造函数的默认构造函数来解决此问题。例如:

public DatabaseInformation() : this ("defaultName"){}
于 2012-11-26T19:18:20.487 回答