I want to get the collection of all the members that are present in a class. How do I do that? I am using the following, but it is giving me many extra names along with the members.
Type obj = objContactField.GetType();
MemberInfo[] objMember = obj.GetMembers();
String name = objMember[5].Name.ToString();
Get a collection of all the properties of a class 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;
for the example to work.
From msdn, members of a class include:
Fields
Constants (comes under Fields)
Properties
Methods
Events
Operators
Indexers (comes under Properties)
Constructors
Destructors
Nested Types
When you do GetMembers
on a class you get all of these (including static ones defined on the class like static/const/operator, not to mention the instance ones) of that class and the instance members of the classes it inherited (no static/const/operator of base classes) but wouldn't duplicate the overridden methods/properties.
To filter out, you have GetFields
, GetProperties
, GetMethods
, and for greater flexibility, there is FindMembers
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
Which is what I expected, remember, just because your class inherits from somewhere, there are other things provided by default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With