sca*_*t17 1 c# inheritance ironpdf
我在思考如何正确包装我正在使用的名为 .pdf 的 PDF 库时遇到了一个问题IronPDF
。
IronPDF
有一个PdfDocument
对象。
我的想法是创建一个IronPdfDocument
如下所示的对象:
public class IronPdfDocument : PdfDocument, IPdfDocument
{
public IronPdfDocument(string filePath) : base(filePath) { }
public IronPdfDocument(Stream stream) : base(stream) { }
public IronPdfDocument(byte[] data) : base(data) { }
public Stream GetSTream() => base.Stream;
}
Run Code Online (Sandbox Code Playgroud)
IronPDF
还有一个被调用的渲染对象HtmlToPdf
,我的想法是创建一个IronPdfRenderer
如下所示的渲染对象:
public class IronPdfRenderer : HtmlToPdf, IPdfRenderer
{
public IronPdfRenderer() : base() { }
public IPdfDocument RenderHtmlAsPdf(string html)
=> (IronPdfDocument)base.RenderHtmlAsPdf(html);
}
Run Code Online (Sandbox Code Playgroud)
然后在代码中使用接口对象,如下所示:
public IPdfDocument Execute()
{
IPdfRenderer renderer = new IronPdfRenderer();
return renderer.RenderHtmlAsPdf(myHtmlString);
}
Run Code Online (Sandbox Code Playgroud)
IronPdfRenderer
但是,当调用RenderHtmlAsPdf
尝试将IronPDF
's转换PdfDocument
为我的包装对象时,我的对象中出现错误IronPdfDocument
。
我明白,从表面上看,aPdfDocument
可能无法投射到我的IronPdfDocument
, but I would like to create a more generic structure in my code that would help future proof my business logic as different Pdf Libraries can come and go. I was wondering if anyone could provide any help/insight into what I am doing wrong here?
对于任何有兴趣的人来说,这是错误:
Unable to cast object of type 'IronPdf.PdfDocument' to type 'MyNamespace.Merge.IronPdfDocument'.
Run Code Online (Sandbox Code Playgroud)
您无法直接转换为 IronPdfDocument,因为它没有实现与PdfDocument实现的接口相同的接口,作为解决方法,您可以创建一个新对象并将结果流传递给构造函数以创建一个新对象并将其返回,如下所示
public IPdfDocument RenderHtmlAsPdf(string html)
{
var doc= base.RenderHtmlAsPdf(html);
return new IronPdfDocument(doc.Stream);
}
Run Code Online (Sandbox Code Playgroud)