+ -
当前位置:首页 → 问答吧 → 求助 关于反射获得属性

求助 关于反射获得属性

时间:2011-12-06

来源:互联网

C# code
 
public partial class Person: System.Web.UI.Page
    {
        public string Name { get; set; }
        public int Age { get; set; }

        public string GetStr(Person person)
        {
            string str= "";
            PropertyInfo[] proInfo = json.GetType().GetProperties();//获取所有公共属性
            foreach (PropertyInfo p in proInfo)
            {  
               //这里我怎么控制得到的属性呢,就是我只要获得Name和Age属性,其它系统的属性我不想获得,
               //要怎么过滤呢?
               str += p.Name;
               str += p.GetValue(person, null));
            }
            return str;
        }

作者: xpjxbb   发布时间: 2011-12-06

C# code
public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public static string GetStr(Person person)
    {
        string str= "";
        PropertyInfo[] proInfo = person.GetType().GetProperties();//获取所有公共属性
       
        foreach (PropertyInfo p in proInfo)
        {
            if (p.Name != "Name" && p.Name != "Age") continue;
            str += p.GetValue(person, null)+Environment.NewLine;
        }
        return str;
    }
}

作者: wuyazhe   发布时间: 2011-12-06

//这里我怎么控制得到的属性呢,就是我只要获得Name和Age属性,其它系统的属性我不想获得,
  //要怎么过滤呢?
  str += p.Name;
  str += p.GetValue(person, null));

=>

if(p.Name=="Name"||p.Name=="Age")
{
  str += string.Format("{0}:{1}",p.Name,p.GetValue(person, null));
}

作者: Sandy945   发布时间: 2011-12-06

用if判断属性名称是Name和Age

作者: skyparty   发布时间: 2011-12-06

不是啊 我这里只是举个例子 实际我是不知道这个类有哪些属性的,所以上面的方法不行呢@@

作者: xpjxbb   发布时间: 2011-12-06