Reflect a structure

  • Thread starter Thread starter Ian Williamson
  • Start date Start date
I

Ian Williamson

Assuming I have the following structure within a class:

class myClass
{
public struct Action
{
public const String REQUIRED = "T";
public const String IGNORE = "F";
public const String OPTIONAL = "O";
}

... code ...
}

How can I use reflection to access the elements of the
structure?

I can get the structure as such:
typeof(myClass).GetMember("Action",
BindingFlags.Public|BindingFlags.Static), but I am
stymied on how to delve into it.

Cheers, Ian Williamson
 
Ian Williamson said:
Assuming I have the following structure within a class:

class myClass
{
public struct Action
{
public const String REQUIRED = "T";
public const String IGNORE = "F";
public const String OPTIONAL = "O";
}

... code ...
}

How can I use reflection to access the elements of the
structure?

I can get the structure as such:
typeof(myClass).GetMember("Action",
BindingFlags.Public|BindingFlags.Static), but I am
stymied on how to delve into it.

Hi Ian,

Try this:

Type outerType = typeof(myClass);

Type innerType = outerType.GetNestedType("Action",
BindingFlags.Public|BindingFlags.Static);

Console.WriteLine("innerType: {0}\n", innerType.ToString());

FieldInfo[] fields = innerType.GetFields();

foreach (FieldInfo field in fields)
{
Console.WriteLine("Type: {0} Name: {1}",
field.FieldType, field.Name);
}

Console.ReadLine();

Joe
 
That's the ticket. Thanks Joe.

Ian
-----Original Message-----
Assuming I have the following structure within a class:

class myClass
{
public struct Action
{
public const String REQUIRED = "T";
public const String IGNORE = "F";
public const String OPTIONAL = "O";
}

... code ...
}

How can I use reflection to access the elements of the
structure?

I can get the structure as such:
typeof(myClass).GetMember("Action",
BindingFlags.Public|BindingFlags.Static), but I am
stymied on how to delve into it.

Hi Ian,

Try this:

Type outerType = typeof(myClass);

Type innerType = outerType.GetNestedType("Action",
BindingFlags.Public|BindingFlags.Static);

Console.WriteLine("innerType: {0}\n", innerType.ToString());

FieldInfo[] fields = innerType.GetFields();

foreach (FieldInfo field in fields)
{
Console.WriteLine("Type: {0} Name: {1}",
field.FieldType, field.Name);
}

Console.ReadLine();

Joe
--
http://www.csharp-station.com


.
 
Back
Top