获取班级所有成员的集合

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;示例正常工作.

  • 我做了一个简短的 *dotnetfiddle* 来演示用法:https://dotnetfiddle.net/qcWcGA (2认同)

naw*_*fal 6

msdn,班级成员包括:

字段

常量(来自Fields)

属性

方法

活动

运营商

索引器(属于属性)

构造函数

析构函数

嵌套类型

当你GetMembers对一个类进行操作时,你会获得该类的所有这些(包括在类上定义的静态类,如静态/ const /运算符,更不用说实例)和它继承的类的实例成员(没有static/const) /基类的运算符)但不会复制重写的方法/属性.

要过滤掉,你有GetFields,GetPropertiesGetMethods,并且为了更大的灵活性,有FindMembers