class Student
{
    private int no;
    private string name;
    private string namelast;    public Student()
    {    }    public int No
    {
        get { return no; }
        set { no = value; }
    }    public string Name
    {
        get { return name; }
        set { name = value; }
    }
    public string NameList
    {
        get { return namelast; }
        set { namelast = value; }
    }    public void Test()
    {
        Student student = new Student();
        //现在需要构造一个函数实现以下功能
        GetPropertyTypes(student, "Name");//应该返回两个PropertyType属性 Name,NameList
        GetPropertyTypes(student, "No");//返回一个PropertyType
        GetPropertyTypes(student, "aa");//返回NULL
        //实现需求: 根据对象来搜索包含传入字符串的属性,并以对象的形式返回
    }
}

解决方案 »

  1.   

    ]
    /// <summary>
            /// 
            /// </summary>
            /// <param name="className">要查找的类名(完整路径)</param>
            /// <param name="strName">查找的属性名</param>
            /// <returns></returns>
            private ArrayList GetPropertyTypes(string className, string strName)
            {
                ArrayList al = new ArrayList();
                Type type = Type.GetType(className);
                if (type != null)
                {
                    PropertyInfo[] infos = type.GetProperties();
                    foreach (PropertyInfo p in infos)
                    {
                        if (p.Name.Contains(strName))
                        {
                            al.Add(p.Name);
                        }
                    }
                }
                return al;
            }
      

  2.   


    private ArrayList GetPropertyTypes(Student className, string strName)
            {
                ArrayList al = new ArrayList();            Type type = className.GetType();
                if (type != null)
                {
                    PropertyInfo[] infos = type.GetProperties();
                    foreach (PropertyInfo p in infos)
                    {                    
                        if (p.Name.Contains(strName))
                        {
                            al.Add(p.GetValue(className, null));
                            
                        }
                    }
                }
                return al;
            }