C#应用程序设置不使用自定义类保存

时间:2009-05-18 21:26:28

标签: c# class settings appsettings

这是我试图存储的课程

 [Serializable]
[XmlRoot(ElementName = "Database", IsNullable = false, Namespace = "http://somesite.com")]

class Database
{
    [XmlAttribute(AttributeName = "Name")]   
    public string Name { get; set; }

    [XmlAttribute(AttributeName = "Provider")]
    public DatabaseProvider Provider { get; set; }

    [XmlAttribute(AttributeName = "Driver")]
    public string Driver { get; set; }

    [XmlElement("DatabaseEntry")]
    public List<DatabaseEntry> SavedEntries { get; set; }

    public Database()
    {
        SavedEntries = new List<DatabaseEntry>();
    }

    public Database(string type, string provider, string driver)
    {

        Name = type;
        Driver = driver;
        Provider = DatabaseProvider.SqlClient;

        Provider = SetProvider(provider);
        SavedEntries = new List<DatabaseEntry>();
    }

    private DatabaseProvider SetProvider(string provider)
    {
        switch (provider)
        {
            case "OleDb":
                return DatabaseProvider.OleDb;
            case "SqlClient":
                return DatabaseProvider.SqlClient;
            default:
                return DatabaseProvider.SqlClient;
        }
    }
}

[Serializable]
[XmlRoot(ElementName = "DatabaseEntry", IsNullable = false, Namespace = "http://somesite.com")]

class DatabaseEntry

{
    [XmlAttribute(AttributeName = "Name")]
    public string Name { get; set; }

    [XmlAttribute(AttributeName = "ConnectionString")]
    public string ConnectionString { get; set; }

    [XmlAttribute(AttributeName = "DsnString")]
    public string DsnString { get; set; }

    public DatabaseEntry()
    { }
}

数据库是我正在尝试存储的父类,任何人都看错了什么?当我实例化该类并保存它时,没有任何东西得到保存。是什么给了什么?

EDIT!用于保存的代码:

if (Settings.Default.SqlDatabase == null) 
   { 
      Settings.Default.SqlDatabase = CreateNewDatabase();
      Settings.Default.Save();
   }

private Database CreateNewDatabase()
{
    Database data = new Database("SQL Server", "SqlClient", "SQL Native Client");
    data.SavedEntries.Add(new DatabaseEntry()
    {
        Name = "Default",
        ConnectionString = @"Hello1",
        DsnString = @"Hello2"
    });
    return data;
}

我只是想将一个Database类的实例存储到AppSettings

1 个答案:

答案 0 :(得分:5)

您可以尝试制作课程public - XmlSerializer对此很挑剔。

但是,我似乎记得设置代码对类型转换器更感兴趣;你可以尝试为它写一个TypeConverter吗?