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

孤者浪人 提交于 2020-01-04 13:14:05

问题


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


回答1:


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).




回答2:


foreach (MemberInfo mi in tt.GetType().GetMembers()) ...


来源:https://stackoverflow.com/questions/339792/c-sharp-vs-2005-how-to-get-a-classs-public-member-list-during-the-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!