Reflection newbie help request.

M

Mark S.

Hello,

In the code below I'm able to get it to generate:
Name: myList1
Name: myList2

How can I get it to output something like:
myList1 ID: 123
myList2 ID: null or not in list

using System;
using System.Reflection;

public class TestIDClass
{
public volatile string ID;
}

public static class TestListClass
{
public static List<TestIDClass> myList1 = new List<TestIDClass>();
public static List<TestIDClass> myList2 = new List<TestIDClass>();
}

static class test
{
static void Main(string[] args)
{
TestIDClass myIDClass = new TestIDClass();
myIDClass.ID = "123";
TestListClass.myList1.Add(myIDClass);

Type myType = typeof(TestListClass);
try
{
FieldInfo[] myFields = myType.GetFields(BindingFlags.Static |
BindingFlags.Public);
for (int i = 0; i < myFields.Length; i++)
{
Console.WriteLine("Name: " + myFields.Name);
}
}
catch (Exception ex)
{
Console.WriteLine("Exception {0}", ex);
}
}
}


TIA,

M
 
M

Mattias Sjögren

Type myType = typeof(TestListClass);
try
{
FieldInfo[] myFields = myType.GetFields(BindingFlags.Static |
BindingFlags.Public);
for (int i = 0; i < myFields.Length; i++)
{

Is this what you had in mind?

List<TestIDClass> list = myFields.GetValue(null) as
List<TestIDClass>;
if (list != null && list.Count > 0)
Console.WriteLine(myFields.Name + " ID: " + list[0].ID);
else
Console.WriteLine(myFields.Name + " ID null or...");


Mattias
 
M

Mark S.

Thank you very much, that's exactly what I needed. More importantly I have
learned something by studying your example. Cheers.
 

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