对属性进行反序列化不会起作用,但可以在TestProject和Generic-Lists中使用

时间:2014-08-01 07:48:42

标签: c# xml serialization properties deserialization

我的ApplicationSettings-Class的反序列化有一个反弹奇怪的问题。 该课程如下:

[Serializable]
public class ApplicationSettings
{
    public string SelectedGeneralSetting { get; set; }
    public string SelectedCheckSetting { get; set; }
    public string SelectedDataBaseSetting { get; set; }
    public string SelectedCompareSetting { get; set; }

    public List<GeneralSetting> GeneralSettings = new List<GeneralSetting>();
    public List<CheckSetting> CheckSettings = new List<CheckSetting>();
    public List<DataBaseSetting> DataBaseSettings = new List<DataBaseSetting>();
    public List<CompareSetting> CompareSettings = new List<CompareSetting>();

    public ApplicationSettings()
    {

    }
}

此类的序列化工作正常,但反序列化不起作用,公共属性SelectedGeneralSetting,SelectedCheckSetting,SelectedDataBaseSetting和SelectedCompareSetting为null。我正在使用这种方法反序列化:

private void deserialize()
{
    XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings));
    FileStream file = new FileStream(ApplicationSettingsPath + @"\settings.xml", FileMode.Open);
    ApplicationSettings = (serializer.Deserialize(file) as ApplicationSettings);
    file.Close();
 }

有两个奇怪的事情,列表也包含很多属性,并且它们正确地去除了。我创建了一个测试项目,包含一个公共成员和属性以及一个通用列表,所有这些项目都被成功反序列化。我真的不知道为什么它不适用于我的“主项目”。有没有人有建议?反序列化如何表现得如此奇怪? 问候!

2 个答案:

答案 0 :(得分:0)

此代码适用于我。

    private void Form1_Load(object sender, EventArgs e)
            {
                XmlSerializer serializer = new XmlSerializer(typeof(ApplicationSettings));
                XmlReader reader = XmlReader.Create(new StringReader(
                    @"<?xml version=""1.0""?> <ApplicationSettings>
 <SelectedGeneralSetting>Default</SelectedGeneralSetting>
    <GeneralSettings>
    <GeneralSetting><Name>DDD</Name></GeneralSetting>
    </GeneralSettings></ApplicationSettings>"));
                var result = (serializer.Deserialize(reader) as ApplicationSettings);
            }

            [Serializable]
            public class ApplicationSettings
            {
                public string SelectedGeneralSetting { get; set; }
                public List<GeneralSetting> GeneralSettings = new List<GeneralSetting>();
            }

            public class GeneralSetting
            {
                public string Name { get; set; }
            }

检查示例文本中的[BR]文本

答案 1 :(得分:0)

您是否遗漏了deserialize()中的变量名称?

应该是:

ApplicationSettings settings = (serializer.Deserialize(file) as ApplicationSettings);