假设有下面一个类,在程序中已初始化,如何获取里面的变量成员name,age,onduty及其值呢?
public class Employee { public string name; public int age; public bool onduty; }
上测试代码:
private void button1_Click(object sender, EventArgs e) { Employee employee = new Employee { name = "Dejex", age = 30, onduty = true }; System.Reflection.FieldInfo[] members = employee.GetType().GetFields(); foreach (var m in members) { string name = m.Name; //获取变量名 var value = m.GetValue(employee); //获取变量值 } }
用以上句子可以获取变量名和变量值。
扩展:
System.Reflection.MemberInfo[] members = employee.GetType().GetMembers();//获取所有成员,包括方法成员 var mtype=member.MemberType; //成员类型,method,field...
其他属性啦、接口啦...都有相应的方法可以获取