我现在有一个已经生成的对象,还有一个string,该string是对象中一个属性的名称。
我想通过这个string找到对应的属性的值,应该怎么做?

解决方案 »

  1.   


    //没太看明白
    //设Users是登陆用户的一个实体类,其中有Username,Password两个属性
    Users userInfo = new Users();
    userInfo.Username = "tom";
    userInfo.Password = "111";
    string search = "UserName";
    string temp = string.Empty;  //存放属性的值
    switch(search)
    {
      case "UserName":
        temp = userInfo.UserName;
      case "Password";
        temp = userInfo.Password;
      default:
        ;
    }
      

  2.   


    /*here*/using System.Reflection;object GetValue(object user,string propName)
    {
        Type t = user.GetType();
        PropertyInfo propInfo = t.GetProperty(propName); /*propName is a public propperytName*/
        return propInfo.GetValue(user,null); 
    }请注意进行异常处理。
      

  3.   

    刚才又查了一下,c#的switch可以用string做参数,那这两种方法哪个好呢?