序列化树视图时丢失数据 [英] Lost data when serializing treeview

查看:40
本文介绍了序列化树视图时丢失数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 C# 编写一个程序,该程序将数据分配给一个类,然后将该类分配给树视图节点的标签值.

I am writing a program in C#, which assigns data to a class, then assigns that class to the Tag Value of treeview nodes.

我能够使用我在此处找到的答案将我的树视图序列化为文件:将树视图的内容保存到文件并加载它稍后.

I am able to serialize my treeview to file using an answer I found here: Saving content of a treeview to a file and load it later.

然而,使用这种方法反序列化文件时,所有节点的标签都丢失了,或者更有可能的是,它们甚至没有被序列化.

However, the Tag of all the nodes is lost using this method when de-serializing the file, or more likely, they are not even being serialized in the first place.

使用此方法序列化时是否可以保留节点的 Tag 值?如果是这样,如何?

Is it possible to preserve the Tag value of the Nodes when serialized using this method? If so, how?

推荐答案

通过 BinaryFormatter,您的Tag 对象必须标记为 [Serializable],表示可以通过序列化其公共和私有字段来成功序列化和反序列化.如果如此标记,则它序列化为 TreeNode 的一部分,如 参考来源:

To be serialized successfully by BinaryFormatter, your Tag object must be marked as [Serializable], which indicates that it can be successfully serialized and deserialized by serializing its public and private fields. If it is so marked, then it will be serialized as part of a TreeNode, as is shown by the reference source:

[TypeConverterAttribute(typeof(TreeNodeConverter)), Serializable,
DefaultProperty("Text"),    
SuppressMessage("Microsoft.Usage", "CA2240:ImplementISerializableCorrectly")]
public class TreeNode : MarshalByRefObject, ICloneable, ISerializable {

    object userData;

    protected virtual void Serialize(SerializationInfo si, StreamingContext context) {

        // SNIP storage of irrelevant fields.

        if (userData != null && userData.GetType().IsSerializable) {
            si.AddValue("UserData", userData, userData.GetType());
        }
    }

    public object Tag {
        get {
            return userData;
        }
        set {
            userData = value;
        }
    }
 }

请注意,如果您的 Tag 对象不可 可序列化,它将被悄悄跳过;不会抛出异常.

Note that, if your Tag object is not serializable, it will be silently skipped; no exception will be thrown.

这篇关于序列化树视图时丢失数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆