Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 3331
  • Last Modified:

Using Reflection to get Member Values

I have multiple functions that each take it in a different struct to place all the struct's member values into a contigous string buffer, and returns that string. I'm thinking of replacing them with a generic function that uses Reflection. The function will look like this:

private string PrepareData(object obj)
{
     string RetString = string.Empty;

     Type objType = obj.GetType();

     System.Reflection.MemberInfo[] memberList = objtype.GetMembers();
     
     foreach (System.Reflection.MemberInfo mi in memberList)
     {
           // get the member name mi.Name
           .....
           .....
           // now what? how do I get the obj's values?
           ......
           RetString += obj.???.ToString();
     }
     return RetString;
}

Is this doable at all?  Or the answer lies in Reflection.PropertyInfo?

0
Barbless
Asked:
Barbless
1 Solution
 
rallsaldoCommented:
Hi,
Is the following any help? (typing from memory so syntax maybe slightly out)
private string PrepareData(object obj)
{
     string RetString = string.Empty;
     Type objType = obj.GetType();
     System.Reflection.PropertyInfo[] pi = objType.GetProperties();
     foreach (System.Reflection.PropertyInfo property in pi)
        {
         object value = property.GetValue(o, null);
         RetString += value.tostring()
        }
     return RetString;
}

R
0
 
BarblessAuthor Commented:
I tried but "pi" is empty at runtime. I don't know why that is. Could it be the object passed in is a Struct (ValueType?), or because there are no accompanying get() and set() methods associated with each data member in my struct definition?

Anyway, I tried using FieldInfo instead, it works beautifully until it gets to an array of subStructs because the whole array appears to be just a field. And additional code is needed to drill down onto each field of the struct array. It looks very messy.  Has anyone done something like this?
0

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now