using reflection to discover a nested structure

B

bill

All,

Can anyone supply an example or reference to an example of using
reflection to determine the data types contained in a nested stucture
in C#? Once I get the list of MemberInfo[] and determine that
MemberInfo.MemberType.ToString().Equals("NestedType"), I cannot
figure out how to drill down from that point.


TIA,


Bill
 
C

Chris Dunaway

bill said:
All,

Can anyone supply an example or reference to an example of using
reflection to determine the data types contained in a nested stucture
in C#? Once I get the list of MemberInfo[] and determine that
MemberInfo.MemberType.ToString().Equals("NestedType"), I cannot
figure out how to drill down from that point.


You would have to use Activator.CreateInstance to get a reference to
the NestedType and then use the same method to drill down.

I think it would be something like this:

ClassA aObj = new ClassA();
Type t = aObj.GetType();

ClassB b = t.InvokeMember("membername", BindingFlags.GetProperty, null,
aObj, null) as ClassB;

So if "membername" is a property of ClassA that is an instance of
ClassB, the InvokeMember line will get a reference to that member.

I'm now sure how you would change this for your NestedType, but it
should be similar.

Chris
 
D

Dave Sexton

Hi Bill,

Think of it like this: If you knew that a MemberInfo instance was a property,
you would cast it to PropertyInfo. And if a MemberInfo was a field, then you
could cast it to FieldInfo. So what do you cast a MemberInfo to that is a
nested Type? Type. (TypeInfo would be semantically equivalent to Type, so
there is no need for a TypeInfo class :)

class Outer
{
public class Inner
{
public int AField;
}
}

class Program
{
static void Main()
{
foreach (MemberInfo member in typeof(Outer).GetMembers())
{
if (member.MemberType == MemberTypes.NestedType)
{
// MemberInfo that is a NestedType is just a Type itself
Type nestedType = (Type) member;

Console.WriteLine("Members of {0}: ", nestedType);
Console.WriteLine();

foreach (MemberInfo nestedMember in nestedType.GetMembers())
{
Console.WriteLine("Nested Member: " + nestedMember.Name);
}
}
}
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top