本帖最后由 xpjxbb 于 2011-12-06 11:16:36 编辑

解决方案 »

  1.   

    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;
        }
    }
      

  2.   

    //这里我怎么控制得到的属性呢,就是我只要获得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));
    }
      

  3.   

    foreach (PropertyInfo p in proInfo)
                {  
                  p.Name; 
                }
    实际上p.Name就是属性名呀!任何对象都可以采购这个办法的.
    但在实际应用中要注意属性的可读性和可写性.//只读属性(System.Reflection.PropertyInfo 的 CanWrite为False)
            private string _Age;        public string Age
            {
                get { return _Age; }
            }        System.Reflection.PropertyInfo s;        /// <summary>
            /// 但这个反谢后取的的属性 (System.Reflection.PropertyInfo 的 CanWrite为True)
            /// </summary>
            public string Age
            {
                get;
                private set;
            }
                 
      

  4.   

    我的意思是我只想取到我业务上有用的那些属性;那些.net自动声明的属性我想过滤掉
      

  5.   

    获取到那个属性是.net 声明的?
      

  6.   

    foreach (PropertyInfo p in proInfo)
                {  
    循环中加判断foreach (PropertyInfo p in proInfo)
    {  
    if (p.DeclaringType==person.GetType())
    {
    str += p.Name;
    //....
      

  7.   

    PropertyInfo.DeclaringType  获取声明该成员的类。 
      

  8.   


    谢谢  其它属性是Page类声明的 嘿嘿 你理解了我的意思 谢谢
      

  9.   

    我自己绕糊涂了  实际上用的是model里的类 没有继承Page的 我测试的时候直接在页面写了几个属性,页面是继承了Page的  所以就多出了那么多属性