我在序列化方面遇到了很大的问题。 我不知道问题出在哪里,但我可以在类里面展示所有元素。
我用节点做了图。 但唯一的问题。
我使用接口(interface)来实现一种用于连接的元素。 示例 bool 可以连接 bool 等。
我有
[Serializable]
public class Node : IElement
{
//More Constructor..
public IEnumerable<NodeConnection> Connections { get { return connections; } }
public IEnumerable<NodeItem> Items { get { return nodeItems; } }
public ElementType ElementType { get { return ElementType.Node; } }
}
ElementType 是一个接口(interface)
使用节点:IElement
public interface IElement
{
ElementType ElementType { get; }
}
在序列化时我有这个错误
BinaryFormatter bin = new BinaryFormatter();
FileStream fs = new FileStream(sv.FileName, FileMode.Create, FileAccess.ReadWrite);
bin.Serialize(fs,graph.graphNode); //Error here
程序集“Graph, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null”中的类型“Example”未标记为可序列化。
Serialization方法中的graph.graphNode是一个简单的List 有人有想法吗?
最佳答案
如果表单名为 class Example {},那么您可能有一个或多个事件处理程序绑定(bind)到您的节点或节点项。例如,如果 Node 和/或 NodeItem 实现了 INotifyPropertyChanged 并且表单(示例类)绑定(bind)到 PropertyChanged,则 bin.Serialize() 会尝试序列化整个表单。
解决方法:使用
[field: NonSerialized]
在你想要序列化的类中的所有事件上,如果它们被不打算序列化的类消耗:
例如:
[field: NonSerialized]
public event PropertyChangedEventHandler PropertyChanged;
更准确地说:
public class Example : Form
{
Node _node;
public Example()
{
_node = new Node();
_node.MyEvent += _node_MyEvent; // This will cause the BinaryFormatter to try to serialize Example form when serializing _node - unless [field: NonSerialized] attribute is used.
}
private void _node_MyEvent(object sender, EventArgs e)
{
}
}
[Serializable]
public class Node
{
[field: NonSerialized]
public event EventHandler MyEvent;
}
编辑
如果一个可序列化的类引用一个不可序列化的对象,也是如此:
[Serializable]
class Connection
{
// Use [NonSerialized] attribute to prevent serialization of this reference:
[NonSerialized]
public Example; // A reference to a non serialized object
}
关于C#帮助序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40344872/