简体   繁体   English

如何在iTextSharp中使用反射取回值

[英]How to get back the value using reflection in iTextSharp

I have a requirement in which user select the size of pdf that is generated dynamically. 我要求用户选择动态生成的pdf大小。

To populate all sizes supported by iTextSharp I am enumerating all sizes in a dropdownlist as 为了填充iTextSharp支持的所有尺寸,我在下拉列表中列举了所有尺寸,如下所示:

      System.Reflection.FieldInfo[] fi = typeof(iTextSharp.text.PageSize).GetFields();
      DropDownList1.DataSource = fi;
      DropDownList1.DataBind();

Every thing is ok till here. 到这里一切都还可以。 Now when user select say letter size, how can i use this information for initializing the document which is initialized like 现在,当用户选择说字母大小时,我如何使用此信息来初始化像

var document = new Document(PageSize.LETTER);

Currently i am trying to get it like this but its giving compile type error. 目前,我正试图使它像这样,但它给编译类型错误。

PageSize getpsize()
 {
      System.Reflection.FieldInfo[] fi = typeof(iTextSharp.text.PageSize).GetFields();
      int si = DropDownList1.SelectedIndex;
      PageSize p = fi[si];
      return p;
 }

Please help as this is my first serious experience with reflection. 请帮忙,因为这是我第一次认真思考。

System.Reflection.FieldInfo[] fi = typeof(iTextSharp.text.PageSize).GetFields();

FieldInfo[] is array of fields metadata, not the objects themselves. FieldInfo[]是字段元数据的数组,而不是对象本身。

So after you get the necessary metadata, you need to get actual field value like this: 因此,在获取必要的元数据之后,您需要获取如下所示的实际字段值:

FieldInfo field = fi[si];
PageSize size = (PageSize)field.GetValue(null);

GetValue(object) returns actual value of the field. GetValue(object)返回该字段的实际值。 As these fields are static, you pass null, as there is no specific object to query. 由于这些字段是静态的,因此您将传递null,因为没有要查询的特定对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM