我正在学习c#中的思考概念.我有这样的课
public class pdfClass
{
public List<AttributeProperties> TopA { get; set; }
public List<AttributeProperties> TopB { get; set; }
public List<AttributeProperties> TopC { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
在另一个类中,我想从列表中提取值.我有愚蠢的方法来做它
public void ExtractValue (pdfClass incomingpdfClass, string type)
{
switch (type)
{
case "TopA":
foreach (var listitem in incomingPdfClass.TopA)
{...}
breaks;
case "TopB":
foreach (var listitem in incomingPdfClass.TopB)
{...}
breaks;
...
}
}
Run Code Online (Sandbox Code Playgroud)
foreach循环中的操作类似.如何通过使用反射以清晰的方式完成此操作?
public void ExtractValue(pdfClass incomingpdfClass, string type)
{
PropertyInfo pinfo = typeof(pdfClass).GetProperty("Top" + type);
var yourList = pinfo.GetValue(incomingpdfClass);
foreach (var listitem in yourList)
{ ... }
}
Run Code Online (Sandbox Code Playgroud)
这是你应该如何使用反射来做到这一点.但是,您应该注意到我的代码与您的代码不同之处在于您编写的代码不清楚也不会编译.如
public class ExtractValue (pdfClass incomingpdfClass, string type)
Run Code Online (Sandbox Code Playgroud)
是无效的C#语法,如果它应该是一个函数,根据我的例子,这将适合你
或者如果这应该发生在Constructor
类中,它应该如下所示
public class ExtractValue
{
public ExtractValue(pdfClass incomingpdfClass, string type)
{
PropertyInfo pinfo = typeof(pdfClass).GetProperty("Top" + type);
var yourList = pinfo.GetValue(incomingpdfClass);
foreach (var listitem in yourList)
{ ... }
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
188 次 |
最近记录: |