2
在我正在處理的代碼中,有一些屬性被序列化。儘管我可以看到它們都很好,但只有一個。下面的代碼:XML串行器不能在屬性上工作
// Fields that the properties use.
private bool _useAlertColors = false;
private List<Int32> _colorArgb = new List<Int32>(new Int32[]{Color.White.ToArgb(), Color.Yellow.ToArgb(), Color.Red.ToArgb()});
// The one that does not work.
public List<Color> AlertColors
{
get
{
List<Color> alertColors = new List<Color>();
foreach (Int32 colorValue in _colorArgb)
{
alertColors.Add(Color.FromArgb(colorValue));
}
return alertColors;
}
set
{
// If there's any difference in colors
// then add the new color
for (int i = 0; i < _colorArgb.Count; i++)
{
if (_colorArgb[i] != value[i].ToArgb())
{
_colorArgb[i] = value[i].ToArgb();
HasChanged = true;
}
}
}
}
// One of those that work.
public bool UseAlertColors
{
get
{
return _useAlertColors;
}
set
{
if (_useAlertColors != value)
{
_useAlertColors = value;
HasChanged = true;
}
}
}
// Serializing method.
public bool Serialize(string filePath)
{
if (string.IsNullOrEmpty(filePath))
{
Logger.Log("Can't save settings, empty or null file path.");
return false;
}
FileStream fileStream = null;
try
{
fileStream = new FileStream(filePath, FileMode.Create);
FilePath = filePath;
System.Xml.Serialization.XmlSerializerFactory xmlSerializerFactory =
new XmlSerializerFactory();
System.Xml.Serialization.XmlSerializer xmlSerializer =
xmlSerializerFactory.CreateSerializer(typeof(Settings));
xmlSerializer.Serialize(fileStream, this);
Logger.Log("Settings have been saved successfully to the file " + filePath);
}
catch (ArgumentException argumentException)
{
Logger.Log("Error while saving the settings. " + argumentException.Message);
return false;
}
catch (IOException iOException)
{
Logger.Log("Error while saving the settings. " + iOException.Message);
return false;
}
finally
{
if (fileStream != null)
fileStream.Close();
}
return true;
}
序列化之後,這是我結束了:
<UseAlertColors>true</UseAlertColors>
<AlertColors>
<Color />
<Color />
<Color />
</AlertColors>
什麼是錯的AlertColors
財產?爲什麼它沒有序列化?
編輯:我已經相應改變的AlertColors
財產,它仍然是不工作:
public List<int> AlertColors
{
get
{
return _colorArgb;
}
set
{
// If there's any difference in colors
// then add the new color
for (int i = 0; i < _colorArgb.Count; i++)
{
if (_colorArgb[i] != value[i])
{
_colorArgb[i] = value[i];
HasChanged = true;
}
}
}
}
我得到的.xml文件是這樣的:
<AlertColors>
<int>-1</int>
<int>-8355840</int>
<int>-65536</int>
</AlertColors>
哪些在_colorArgb
字段初始化時設置的第一個值。我可以在程序執行期間看到字段的變化,但是當覆蓋屬性被序列化時,它會與基礎字段的初始值進行序列化。
是什麼導致了這個問題?
小點:它也序列化的公共領域,但這並不改變任何東西重要。你完全正確,'Color'對'XmlSerializer'不友好。 –
我改變了代碼,但它仍然不起作用。我已經記錄了這個問題的變化。 – hattenn
改爲使用DataContractSerializer。 – Jaster