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

在窗体程序中添加一个类文件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
    }
}

结果如下:

转载于:https://www.cnblogs.com/sevennight99/archive/2013/04/03/2997449.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值