在我正在处理的代码中,有一些序列化的属性。就我所见,所有这些都能正常工作,但其中一个。这是代码:
// 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
字段时设置的第一个值。我可以在程序执行期间看到字段更改,但是当覆盖属性被序列化时,它会使用基础字段的初始值进行序列化。
导致问题的原因是什么?
答案 0 :(得分:4)
XMLSerializer在序列化时仅使用类的公共属性 - Color Class没有。
这是一个如何绕过它的好例子:http://www.codeproject.com/Articles/2309/NET-XML-Serialization-a-settings-class