识别可填写 PDF 中的不同字段类型

Identify different field types in a fillable PDF

我是 C# 和 PDFsharp 的新手,所以我不确定检查不同字段类型的最佳方法是什么。现在我正在使用以下代码替换文本字段中的值,但这是因为我知道该字段是一个复选框。

但是如果我要循环遍历从 PDF 中获取的字段,我该如何检查该字段是复选框还是文本字段或完全不同的东西?

PdfCheckBoxField currentField = (PdfCheckBoxField)(form["CheckBox2"]);
currentField.Checked = true;

如果我像这样遍历所有字段,我该如何检查字段类型:

for (int i=0; i<form.Count; i++)
{
   field = form.Names[i];
}

我在 PDFsharp 网站上没有找到很多这方面的信息。任何帮助将不胜感激。

确定您为 form["CheckBox2"] 获得哪种表单字段,特别是您可以将其转换为哪个特定表单字段的最自然方法 class,就是简单地确定该字段的类型目的。这可以通过使用 is keyword or by testing for type identity using typeof and GetType():

测试类型兼容性来完成
var currentField = form["CheckBox2"];
if (currentField is PdfCheckBoxField)
{
    // the type of currentField is compatible with PdfCheckBoxField
    PdfCheckBoxField currentCheckBox = (PdfCheckBoxField)currentField;
    ...
}

var currentField = form["CheckBox2"];
if (currentField != null && currentField.GetType() == typeof(PdfCheckBoxField))
{
    // the type of currentField is PdfCheckBoxField
    PdfCheckBoxField currentCheckBox = (PdfCheckBoxField)currentField;
    ...
}

从 C# 7 开始 is keyword supports pattern matching:

var currentField = form["CheckBox2"];
if (currentField is PdfCheckBoxField currentCheckBox)
{
    // the type of currentField is compatible with PdfCheckBoxField
    // a PdfCheckBoxField variable currentCheckBox here already is declared and initialized with currentField
    ...
}