Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple question: Reflections in C#

Tags:

c#

reflection

I am learning the reflections concepts in c#. I have a class like this

public class pdfClass
{
    public List<AttributeProperties> TopA { get; set; }
    public List<AttributeProperties> TopB { get; set; }
    public List<AttributeProperties> TopC { get; set; }

}

In another class I would like to extract the values from the list. I have stupid ways to do it like

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;
   ...
 }
}

The operations in the foreach loops are similar. How can I do this in a clear way by using reflections?

like image 659
Seen Avatar asked Sep 12 '11 15:09

Seen


2 Answers

public void ExtractValue(pdfClass incomingpdfClass, string type)
{
  PropertyInfo pinfo = typeof(pdfClass).GetProperty("Top" + type);
  var yourList = pinfo.GetValue(incomingpdfClass);
  foreach (var listitem in yourList)
  { ... }
}

This is how you should do this using reflection. However, you should note that my code differs from yours in the fact that you are writing code that isn't clear nor would it compile. AS

public class ExtractValue (pdfClass incomingpdfClass, string type)

is non valid C# syntax if that is supposed to be a function as per my example this will work for you

Or if this is supposed to happen in the Constructor for the class it should look as follows

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)
     { ... }
   }
}
like image 94
msarchet Avatar answered Nov 14 '22 22:11

msarchet


var property = this.GetType().GetProperty(type);
foreach (var item in (List<AttributeProperties>)property.GetValue(this, null))
{

}
like image 32
dkackman Avatar answered Nov 15 '22 00:11

dkackman