C# 通过反射获取属性对应的值GetValue

public class User
{
    public int UserId { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }
    public IList student 
    {
        get;
        set;
    }
}

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

User user = new User();
Student stu1 = new Student() { Name = "张三" };
Student stu2 = new Student() { Name = "李四" };
user.student = new List();
user.student.Add(stu1);
user.student.Add(stu2);
user.Username = "admin";
user.Password = "123456";

User user1 = new User();
Student stu3 = new Student() { Name = "二蛋" };
Student stu4 = new Student() { Name = "王二麻子" };
user1.student = new List();
user1.student.Add(stu3);
user1.student.Add(stu4);
user1.Username = "root";
user1.Password = "123";

IList userList = new List();
userList.Add(user);
userList.Add(user1);
//调用方法
PrintPropertyValue(userList);


private void PrintPropertyValue(IList list)
{

    //获取所有属性名称和属性类型         
    PropertyInfo[] infos = typeof(T).GetProperties();
    foreach (PropertyInfo item in infos)
    {
        Console.WriteLine(string.Format("PropertyName:{0},type:{1}",item.Name,item.PropertyType.Name));
    }

    for (int i = 0; i < list.Count ; i++)
    {
     Console.WriteLine(list[i].GetType().GetProperty("Username").GetValue(list[i],null));              
        Console.WriteLine(list[i].GetType().GetProperty("Password").GetValue(list[i], null));
        object obj = list[i].GetType().GetProperty("student").GetValue(list[i],null);
        IList ll = obj as IList;
                
        foreach (var item in ll)
        {
            Console.WriteLine(string.Format("Name:{0},Age:{1}",item.GetType().GetProperty("Name").GetValue(item, null),item.GetType().GetProperty("Age").GetValue(item, null)));                  
        }
    }
}

 

你可能感兴趣的:(C#)