为什么foreach在与itextsharp一起使用时会导致错误

Si8*_*Si8 1 c# pdf foreach visual-studio-2012

部分代码是:

private void ListFieldNames()
        {
            string pdfTemplate = @"c:\Temp\PDF\fw4.pdf";

            // title the form
            this.Text += " - " + pdfTemplate;

            // create a new PDF reader based on the PDF template document
            PdfReader pdfReader = new PdfReader(pdfTemplate);

            // create and populate a string builder with each of the 
            // field names available in the subject PDF
            StringBuilder sb = new StringBuilder();
            foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)
            {
                sb.Append(de.Key.ToString() + Environment.NewLine);
            }

            // Write the string builder's content to the form's textbox
            textBox1.Text = sb.ToString();
            textBox1.SelectionStart = 0;
        }
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

Error 1 Cannot convert type 'System.Collections.Generic.KeyValuePair<string,iTextSharp.text.pdf.AcroFields.Item>' to 'System.Collections.DictionaryEntry' c:\Users\usrs\Documents\Visual Studio 2012\Projects\PDFTest SLN\PDFTest\Form1.cs 50 13 PDFTest

我正在使用VS 2012.

我该如何解决错误?

emp*_*mpi 5

正如错误所说:因为FieldsSystem.Collections.Generic.KeyValuePair<string,iTextSharp.text.pdf.AcroFields.Item>不是的集合DictionaryEntry.

您应该使用显式System.Collections.Generic.KeyValuePair<string,iTextSharp.text.pdf.AcroFields.Item>类型或使用var关键字,让编译器确定类型.

我建议使用以下代码:

foreach (var de in pdfReader.AcroFields.Fields)
{
    sb.Append(de.Key.ToString() + Environment.NewLine);
}
Run Code Online (Sandbox Code Playgroud)