繁体   English   中英

对象的序列化列表失败,出现NullReferenceException

[英]Serialize List of objects fails with NullReferenceException

为了在我的应用程序中支持复制/粘贴,我必须使我的所有对象可序列化,以便能够将它们放入剪贴板并从那里再次获取它们。 只要没有要序列化的List<xy>对象,它就会按预期工作。

这是一个对象的第一部分:

[Serializable]
public class Parameter : GObserverSubject, ISerializable, IObserver
{ 
    #region Attributes
    private static readonly ILog log = LogManager.GetLogger(typeof(Parameter));
    private int priority;
    private string name;
    private int id;
    private string description;
    private string comments;
    private List<Value> values;
    private Container myContainer;
    private bool changed;
    private int order;
    private bool noUpdate;
    #endregion
}

我还实现了这两种方法:

public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
{
    info.AddValue("priority", priority);
    info.AddValue("name", name);
    info.AddValue("id", id);
    info.AddValue("changed", true);
    info.AddValue("order", order);
    info.AddValue("values", values, values.GetType());
}

protected Parameter(SerializationInfo info, StreamingContext context)
{
    priority = info.GetInt32("priority");
    name = info.GetString("name");
    id = info.GetInt32("id");
    values = (List<Value>)info.GetValue("values", values.GetType());
    changed = info.GetBoolean("changed");
    order = info.GetInt32("order");
}

这就是我从TreeView复制和粘贴内容的方式:

Parameter parameter = ((TreeNodeParameter)this.TestDesignTree.SelectedNode).getParameter();
Clipboard.SetDataObject(parameter);

IDataObject iData = Clipboard.GetDataObject();
Object copiedObject = iData.GetData(DataFormats.Serializable);
log.Info("type of selectednode is: " + this.TestDesignTree.SelectedNode.GetType());
log.Info("type of object in clipboard is: " + copiedObject.GetType());

应用程序在NullReferenceExceptioncopiedObject.GetType()处崩溃。

我在这里做错了什么?

似乎唯一的问题是我如何定义对象的类型:

values.GetType()

应该:

typeof(List<Value>);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM