如何在c#中序列化钢笔

本文关键字:序列化 | 更新日期: 2023-09-27 18:18:40

我有一个包含

的Shape类
public Pen outlinePen;  

我要做的是序列化List of Shape,但是我只有Type

System.Drawing。Pen"in Assembly"系统。= 4.0.0.0画画,版本,Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'未标记为可序列化的。

如果我把这个字段标记为[field: NonSerialized()],那么我不能使用我加载的对象,因为outlinePen是空的。

还有其他序列化System.Drawing.Pen的方法吗?

如何在c#中序列化钢笔

应该只序列化您感兴趣的数据。Pen是一个图形对象,所以即使有可能,在我看来,存储它也不是一个好主意。

例如,在您的情况下,您可以存储PenColor, PenWidthPenStyle,就像PenDataObject一样,这是一种Pen轻量级对象,专门创建用于存储Pen数据。

Pen被。net内部标记为不可序列化的,并且它是密封的,因此您也不能子类化和序列化它。如果你需要序列化图形,你可以查看Metafile类,它是专门为存储图形和绘图对象而设计的。

我建议采用一种不同的方法,在父对象被反序列化时执行一些逻辑。

[NonSerialized]
private Pen _penToUse;
[OnDeserialized()]
internal void Reinitialize(StreamingContext context)
{
    SwitchPen(); //now we can restore the Pen, the easy way would be 
                 //to store it in a static class in the domain
}