首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >为什么xmlignore不使用System.Timers.Timer类?

为什么xmlignore不使用System.Timers.Timer类?
EN

Stack Overflow用户
提问于 2016-11-02 21:30:33
回答 2查看 482关注 0票数 0

我试图序列化一个类对象,在添加System.Timers.Timer对象时遇到了一个问题。

在序列化过程中,我将得到以下异常:

代码语言:javascript
复制
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.6WindowsForms应用程序

下面是我正在序列化的类:

代码语言:javascript
复制
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 )

代码语言:javascript
复制
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();
        }
    }

来自评论的

将属性设置为私有-没有帮助

代码语言:javascript
复制
    private System.Timers.Timer timer { get; set; }

使用NonSerialized -没有帮助:

代码语言:javascript
复制
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

“特别是不使用自动属性

代码语言:javascript
复制
 Additional information: Type 'System.Timers.Timer' in Assembly 'System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not marked as serializable.
EN

回答 2

Stack Overflow用户

发布于 2016-11-02 21:35:18

[Serializable]属性使您感兴趣。

因为您使用的是[Serializable]属性,所以您需要为timer属性添加[NonSerialized],详见this answer

票数 0
EN

Stack Overflow用户

发布于 2016-11-02 22:27:36

以下是我必须做的,以完全~忽略计时器对象:

代码语言:javascript
复制
[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);
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/40390155

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档