【发布时间】:2017-03-16 08:49:58
【问题描述】:
我正在尝试序列化一个类对象,但在添加 System.Timers.Timer 对象时遇到了问题。
在序列化过程中,我收到以下异常:
An unhandled exception of type 'System.Runtime.Serialization.SerializationException' occurred in mscorlib.dll
Additional information: Type 'System.Timers.Timer' in Assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
项目是 .net 4.6 Windows Forms 应用程序
这是我要序列化的类:
using System;
using System.Xml.Serialization;
[Serializable]
[XmlInclude(typeof(CTestClass))]
public class CTestClass
{
public CTestClass()
{
x = 1;
timer = new System.Timers.Timer();
}
[XmlElement]
public int x { get; set; }
// It seems [XmlIgnore] is being ignored... :-(
[XmlIgnore]
public System.Timers.Timer timer { get; set; }
}
这是我用来序列化类对象的代码:
(注意:需要使用 BinaryFormatter)
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows.Forms;
private void TestIt()
{
CTestClass ctc = new CTestClass();
SerializeData(ctc);
}
protected virtual byte[] SerializeData(CTestClass data)
{
using (var memoryStream = new MemoryStream())
{
new BinaryFormatter().Serialize(memoryStream, data);
return memoryStream.ToArray();
}
}
来自评论:
将属性设置为私有 - 没有帮助
private System.Timers.Timer timer { get; set; }
使用 [NonSerialized] - 没有帮助:
Error CS0592 Attribute 'NonSerialized' is not valid on this declaration type. It is only valid on 'field' declarations. TimerSerializationError c:\TimerSerializationError\TimerSerializationError\CTestClass.cs 19 Active
“特别是不使用自动属性——(即没有设置)”——没有帮助:
Additional information: Type 'System.Timers.Timer' in Assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
【问题讨论】:
-
您没有使用 XML 序列化,这就是
[XmlIgnore]属性被忽略的原因。只需让你的计时器private- 无论如何你都不太可能想要公开它。 -
将计时器更改为私有 -- SAME 错误
-
很抱歉。也许您可以改用 XmlSerializer,或者从您的类中删除计时器,或者让您的类持有一个“设置”类的实例,其中包含真正的可序列化数据,而只是序列化/反序列化设置类。最后,您还可以选择实现
ISerializable,在这种情况下您可以控制序列化中包含的内容。