为什么xmlignore不能与System.Timers.Timer类一起工作?
本文关键字:一起 工作 Timer Timers xmlignore 不能 System 为什么 | 更新日期: 2023-09-27 18:16:06
我正在尝试序列化一个类对象,当我添加一个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窗体应用程序
这是我要序列化的类:
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 -没有帮助
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
"特别不使用auto-property——(即没有预备)"-没有帮助:
Additional information: Type 'System.Timers.Timer' in Assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
这是[Serializable]
属性让你。
因为您使用的是[Serializable]
属性,所以您需要为您的计时器属性添加[NonSerialized]
,如本答案所述。
为了完全忽略计时器对象,我必须这样做:
[Serializable]
public class CTestClass : ISerializable
{
public CTestClass()
{
x = 1;
timer = null;
}
public int x { get; set; }
private System.Timers.Timer timer { get; set; }
public void GetObjectData(SerializationInfo info, StreamingContext context)
{
info.AddValue("x", x);
}
}