问题
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();
回答1:
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.
回答2:
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
回答3:
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.
回答4:
The code looks correct. Are the extra names you are getting members that are inherited from a base class?
回答5:
Linqpad Demo Program
To make it easy to understand what the code from dknaack does i created a linqpad demo program
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;
}
}
来源:https://stackoverflow.com/questions/6773806/getting-collection-of-all-members-of-a-class