Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# VS 2005: How to get a class's public member list during the runtime?

I'm trying to get a class memeber variable list at run time. I know this probably using typeof and reflections. but can't find an example. Please someone shed light for me.

Here is pseudo code example:

Class Test01
{ 
 public string str01;
 public string str02;
 public int myint01;
}

I want something like this (pseudo code):

Test01 tt = new Test01();
foreach(variable v in tt.PublicVariableList)
{
   debug.print v.name;
   debug.print v.type;
}

Please help me figure out how to do this in C# VS2005

Thanks a lot

like image 271
simon Avatar asked Nov 19 '25 22:11

simon


2 Answers

If you're after public fields just use tt.GetType().GetFields()

If you need other members, use GetProperties(), GetMethods(), GetEvents() etc for specific ones, or GetMembers() to get them all.

Each method has an overload accepting a BindingFlags if you want to access non-public members, or restrict the search to static members (or just to instance members).

like image 77
Jon Skeet Avatar answered Nov 21 '25 12:11

Jon Skeet


foreach (MemberInfo mi in tt.GetType().GetMembers()) ...
like image 45
leppie Avatar answered Nov 21 '25 11:11

leppie