C# 反射方式获取对象的所有属性和方法

定义封装类

public class Test
{

    public string Test1 { set; get; }
    public string Test2 { set; get; }
    public string Test3 { set; get; }
    public string Test4 { set; get; }
    public string Test5 { set; get; }
}

创建对象

Test t = new Test()
{
    Test1 = "1",
    Test2 = "2",
    Test3 = "3",
    Test4 = "4",
    Test5 = "5"
};

获取属性和方法

Type type = typeof(Test);
//获取所有属性。
PropertyInfo[] properties = type.GetProperties();

// 遍历属性打印到控制台。
foreach (PropertyInfo prop in properties)
{
    Console.WriteLine(prop.Name);
    Console.WriteLine(prop.GetValue(t));
}
//object obj = Activator.CreateInstance(type);
 获取所有方法。
//MethodInfo[] methods = type.GetMethods();
 遍历方法打印到控制台。
//foreach (MethodInfo method in methods)
//{
//    Console.WriteLine(method.Name);
//}

 获取所有成员。
//MemberInfo[] members = type.GetMembers();
 遍历成员打印到控制台。
//foreach (MemberInfo member in members)
//{
//    Console.WriteLine(member.Name);
//}