Getting a collection of all class members

I want to get a collection of all the members present in the class. How can I do it? I use the following, but it gives me many additional names along with the members.

Type obj = objContactField.GetType(); MemberInfo[] objMember = obj.GetMembers(); String name = objMember[5].Name.ToString(); 
+9
source share
5 answers

Get a collection of all class properties and their values:

 class Test { public string Name { get; set; } } Test instance = new Test(); Type type = typeof(Test); Dictionary<string, object> properties = new Dictionary<string, object>(); foreach (PropertyInfo prop in type.GetProperties()) properties.Add(prop.Name, prop.GetValue(instance)); 

Note that you will need to add using System.Collections.Generic; and using System.Reflection; so that the example works.

+9
source

Of the msdn class members are:

Fields

Constants (included in the fields)

The properties

Methods

Events

Operators

Indexers (included in Properties)

Constructors

destructors

Nested Types

When you do GetMembers in a class, you get all this (including static class-specific ones such as static / const / operator, not to mention instances) of this class and members of the class instances that it inherited (no static / const / operator base classes), but will not duplicate overridden methods / properties.

For filtering you have GetFields , GetProperties , GetMethods , and for more flexibility there are FindMembers

+6
source

Well, it depends a little on what you get. For example:

  static void Main(string[] args) { Testme t = new Testme(); Type obj = t.GetType(); MemberInfo[] objMember = obj.GetMembers(); foreach (MemberInfo m in objMember) { Console.WriteLine(m); } } class Testme { public String name; public String phone; } 

Returns

 System.String ToString() Boolean Equals(System.Object) Int32 GetHashCode() System.Type GetType() Void .ctor() System.String name System.String phone 

This is what I expected, remember, only because your class is inherited somewhere, there are other things provided by default.

+3
source

The code looks right. Are there any additional names that you get that inherit from the base class?

+2
source

Linqpad Demo

To make it easier to understand what code is doing from dknaack, I created a Linqpad demo

 void Main() { User instance = new User(); Type type = typeof(User); Dictionary<string, object> properties = new Dictionary<string, object>(); foreach (PropertyInfo prop in type.GetProperties()) properties.Add(prop.Name, prop.GetValue(instance)); properties.Dump(); } // Define other methods and classes here class User { private string foo; private string bar { get; set;} public int id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public System.DateTime Dob { get; private set; } public static int AddUser(User user) { // add the user code return 1; } } 
0
source

All Articles