派生 FixedDocument 的序列化

Serialization of derived FixedDocument

由于只能给一个FixedDocument添加页面,所以我写了一个派生class:

public class CustomFixedDocument : FixedDocument
{
    public void RemoveChild(object child)
    {
        base.RemoveLogicalChild(child);
    }
}

替换 FixedDocument,效果很好,直到我尝试打印文档并收到以下错误:

An unhandled exception of type 'System.Windows.Xps.XpsSerializationException' occurred in ReachFramework.dll

Additional information: Serialization of this type of object is not supported.

我过去没有那么多地使用序列化,并且已经阅读了它,但仍然无法解决问题。我也试过

[Serializable]

属性,但没有任何区别。

谁能指导我正确的方向或有什么想法该怎么做?

查看是否支持某个类型的方法的反编译源码,大致如下:

internal bool IsSerializedObjectTypeSupported(object serializedObject)
{
  bool flag = false;
  Type type = serializedObject.GetType();
  if (this._isBatchMode)
  {
    if (typeof (Visual).IsAssignableFrom(type) && type != typeof (FixedPage))
      flag = true;
  }
  else if (type == typeof (FixedDocumentSequence) || type == typeof (FixedDocument) || (type == typeof (FixedPage) || typeof (Visual).IsAssignableFrom(type)) || typeof (DocumentPaginator).IsAssignableFrom(type))
    flag = true;
  return flag;
}

这里你看到这个类型要么继承DocumentPaginator、Visual,要么正好是FixedDocument、FixedDocumentSequence、FixedPage类型。因此,无论您将使用什么可序列化属性,从 FixedDocument 继承的类型都不起作用,因此您必须找到不同的方法。我认为这是 XpsSerializationManager 中的错误,但也许有一些深层原因。

我决定尝试 OP 的方法,看看我能否让它发挥作用。

根据 Evk 发布的代码片段,虽然 IsSerializedObjectTypeSupported() 函数不会接受我们自己自定义的 FixedDocument 派生函数,但它会接受 DocumentPaginator,并且其中一个重载XpsDocumentWriter.Write() 接受分页器,所以应该可以,对吧?

嗯,事实证明,如果你这样做 XpsDocumentWriter.Write( myFixedDocument.DocumentPaginator )(其中 myFixedDocumentFixedDocument 的自定义派生词),那么某些东西会在库的某个深处抛出 NullReferenceException代码。所以,运气不好。

但是,根据同一代码段,FixedPage 也是受支持的类型,并且 XpsDocumentWriter.Write() 方法有另一个重载,它接受 FixedPage.[=24 的各个实例=]

所以,下面的代码对我有用:

foreach( FixedPage fixedPage in 
        fixedDocument.Pages.Select( pageContent => pageContent.Child ) )
    xpsDocumentWriter.Write( fixedPage );

(其中 Select() 来自 using System.Linq