我試圖從xml文件反序列化一些設置。有問題的財產/基礎領域是一個叫AlertColors
。我將基礎字段初始化爲白色,黃色和紅色,以確保此類的新實例具有有效的顏色設置。但是,當我反序列化時,_colorArgb
結束了六個值,前三個是初始化值,最後三個是從xml文件中讀取的值。但屬性AlertColors
不附加到該字段,但更改其元素。爲什麼我最終選擇了六種顏色的領域?Xml反序列化附加到列表
下面的代碼:
private List<int> _colorArgb = new List<int>(new int[] { Color.White.ToArgb(), Color.Yellow.ToArgb(), Color.Red.ToArgb() });
public List<int> AlertColors
{
get
{
return _colorArgb;
}
set
{
for (int i = 0; i < Math.Min(_colorArgb.Count, value.Count); i++)
{
if (_colorArgb[i] != value[i])
{
HasChanged = true;
}
}
_colorArgb = value;
}
}
public bool Deserialize(string filePath)
{
if (!File.Exists(filePath))
{
Logger.Log("Error while loading the settings. File does not exist.");
return false;
}
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath, FileMode.Open);
System.Xml.Serialization.XmlSerializerFactory xmlSerializerFactory =
new XmlSerializerFactory();
System.Xml.Serialization.XmlSerializer xmlSerializer =
xmlSerializerFactory.CreateSerializer(typeof(Settings));
Settings deserializedSettings = (Settings)xmlSerializer.Deserialize(fileStream);
GetSettings(deserializedSettings);
Logger.Log("Settings have been loaded successfully from the file " + filePath);
}
catch (IOException iOException)
{
Logger.Log("Error while loading the settings. " + iOException.Message);
return false;
}
catch (ArgumentException argumentException)
{
Logger.Log("Error while loading the settings. " + argumentException.Message);
return false;
}
catch (InvalidOperationException invalidOperationException)
{
Logger.Log("Error while loading the settings. Settings file is not supported." +
invalidOperationException.Message);
return false;
}
finally
{
if (fileStream != null)
fileStream.Close();
FilePath = filePath;
}
return true;
}
protected void GetSettings(Settings settings)
{
AlertColors = settings.AlertColors;
}
而且說我反序列化XML文件的相關部分:
<AlertColors>
<int>-1</int>
<int>-15</int>
<int>-65536</int>
</AlertColors>
就像一邊:當你的當前值是{白色,白色,藍色}時,你會意識到改變檢測的迭代會錯過例如設置{白色,白色}? – Anton
是的,我在想,如果有兩個值,它是前兩個值。用戶不應該手動改變它們。 – hattenn
相關:http://stackoverflow.com/q/4217139/161052 – JYelton