您的位置:首页 > 其它

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

2013-04-03 10:51 375 查看
在窗体程序中添加一个类文件Student(解决方案右键->添加->类 类名Student。 )

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

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


结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐