San*_*rty 9 c# reflection member
我想获得一个类中所有成员的集合.我怎么做?我使用以下内容,但它给了我许多额外的名字和成员.
Type obj = objContactField.GetType();
MemberInfo[] objMember = obj.GetMembers();
String name = objMember[5].Name.ToString();
Run Code Online (Sandbox Code Playgroud)
dkn*_*ack 10
如果您想要所有属性和值的集合,请执行以下操作:
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));
Run Code Online (Sandbox Code Playgroud)
请注意,您需要添加using System.Collections.Generic;并使using System.Reflection;示例正常工作.