为什么xmlignore不能与System.Timers.Timer类一起使用

时间:2016-11-02 21:30:34

标签: c# timer

我正在尝试序列化一个类对象,并在添加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 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.

2 个答案:

答案 0 :(得分:0)

它是获得你的[Serializable]属性。

由于您使用的是[Serializable]属性,因此您需要为{+ 3}}中详细说明的计时器属性添加[NonSerialized]

答案 1 :(得分:0)

以下是我必须做的事情〜完全忽略了计时器对象:

[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);
    }
}