反射机制访问对象类型——知道对象的某个属性名称得到该属性的值(自己写的列子以后参考用)

在窗体程序中添加一个类文件Student(解决方案右键->添加->类 类名Student。 )

类的属性必须要有get set方法。(此处注意类的属性与字段的区别)

View Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace UseReflection1
{
    public class Student
    {
       public string name { get; set; }//属性必须要有get set
       public int age { get; set; }
    }
}

在Form窗口中放一个label和一个textbox,用于显示属性名称和属性值

Form代码

View Code
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;

namespace UseReflection1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            Student stu = new Student();//实例化对象
            stu.name = "张三";
            stu.age = 24;

            excute(stu, "name");  //类的实体反射得到属性名为name的属性值          
        }
        #region
        /// <summary>
        /// 类的实体反射得到相应名称的属性值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="str"></param>
        public void excute(object obj, string str)
        {
            try
            {
                Type objtype = obj.GetType();//得到对象的类型
                PropertyInfo property = objtype.GetProperty(str);//得到实体中名称为str的属性
                
                if (property != null)
                {
                    label1.Text = property.Name.ToString();//属性名称
                    textBox1.Text = Convert.ToString(property.GetValue(obj, null));//属性值
                }
            }
            catch
            { return; }
        }
        #endregion
    }
}

结果如下:

posted @ 2013-04-03 10:51  sevennight99  阅读(202)  评论(0编辑  收藏  举报