0

亲爱的 Stack Overflow 社区,我以为我永远不必问这个问题,但显然序列化或我对它的使用出了点问题。

我有一个需要序列化的类:

[Serializable]
public class Device : ISerializable, IDisposable
{
   public delegate void ListChangedEventHandler(object sender, ListChangedEventArgs e);
   public string Name { get; set; }
   public string Description { get; set; }
   public string IPAddress { get; set; }

   [Browsable(false)]
   public ThreadSafeBindingList<Item> Items { get; set; }

    [Browsable(false)]
    public MibEntity AssociatedMibEntity { get; set; }

    //methods etc.
}

一点解释:

ThreadSafeBindingList 继承自 System.ComponentModel.BindingList MibEntity 是 SharpSNMP 库的一个类(http://sharpsnmplib.codeplex.com/

问题: 当我尝试反序列化对象时,MibEntity 始终为空。其他属性都还好。MibEntity 类在外部 dll 中,我在 Device 类所在的项目中引用了它。

这是它的内容:

[Serializable]
public class MibEntity 
{
    public MibEntity()
    {
        Children = new List<MibEntity>(); 
    } 

    [Browsable(false)]
    public List<MibEntity> Children { get; set; }

    [Browsable(true)]
    [Category("General")]
    public string OID { get; set; }

    private string _name;
    [Browsable(true)]
    [Category("General")]
    public string Name
    {
        get { return _name; }
        set { _name = value; }
    }

    [Browsable(true)]
    public string Description { get; set; }

    [Browsable(false)]
    public int Value { get; set; }


    [Browsable(true)]
    public AccessType AccessType { get; set; } //this is enum from SharpSNMP library

    [Browsable(true)]
    public Status Status { get; set; } //this is enum from same assembly as this class

    [Browsable(true)]
    public string Syntax { get; set; }

    [Browsable(true)]
    public bool IsTableEntry { get; set; }

    [Browsable(true)]
    public IDefinition IDefinition { get; set; } //this is interface from SharpSNMP library
}

我使用 BinaryFormatter 进行序列化和反序列化。感谢您的帮助!

4

1 回答 1

3

这总是意味着您在自定义ISerializable实现中犯了错误;以下工作正常:

protected Device(SerializationInfo info, StreamingContext context)
{
    Name = info.GetString("Name");
    //...
    AssociatedMibEntity = (MibEntity)info.GetValue(
        "AssociatedMibEntity", typeof(MibEntity)); 
}
void ISerializable.GetObjectData(
    SerializationInfo info, StreamingContext context)
{
    info.AddValue("Name", Name);
    //...
    info.AddValue("AssociatedMibEntity", AssociatedMibEntity);
}

经验证:

using (var ms = new MemoryStream())
{
    var bf = new BinaryFormatter();
    bf.Serialize(ms, new Device {
        AssociatedMibEntity = new MibEntity { Name = "Foo"}});
    ms.Position = 0;
    var clone = (Device)bf.Deserialize(ms);
    Console.WriteLine(clone.AssociatedMibEntity.Name); // Foo
}

但是,除非有充分的理由实施 ,否则完全删除ISerializable实施可能会更好地为您服务- 请注意,这将是一个重大更改(如果您这样做,任何现有数据都不会正确反序列化)。ISerializable

[Serializable]
public class Device : IDisposable // <=== no ISerializable; also removed
                                  // GetObjectData and custom .ctor

另外:我通常的咆哮:BinaryFormatter如果您将这些数据存储在任何地方,可能不是您最好的选择。它是……易碎的。有一系列更可靠的序列化器。

于 2013-08-19T08:38:23.150 回答