六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 32|回复: 0

c#利用反射轻松遍历类获取其所有属性及属性值

[复制链接]

升级  74.2%

2220

主题

2220

主题

2220

主题

榜眼

Rank: 8Rank: 8

积分
6710
 楼主| 发表于 2013-1-19 04:09:08 | 显示全部楼层 |阅读模式
利用反射可以轻松的获取这些信息
类的写法:
namespace ClassLibrary1
{
public class Class1
{
   public string Name
   {
     get { return "name"; }
   }
   public string Title
   {
     get { return "title"; }
   }
}
}
使用的时候
private void simpleButton1_Click_1(object sender, EventArgs e)
{
  ClassLibrary1.Class1 cl1 = new ClassLibrary1.Class1();
  string s = string.Empty;
  foreach(System.Reflection.PropertyInfo info in typeof(ClassLibrary1.Class1).GetProperties())
  {
     s += info.Name + "\n";
     s += info.GetValue(cl1, null)+"\n";
  }
  MessageBox.Show(s);
}
输出结果
弹出框内容
Name
name
Title
title
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表