happmaoo 发表于 2013-1-19 04:09:08

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

利用反射可以轻松的获取这些信息
类的写法:
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
页: [1]
查看完整版本: c#利用反射轻松遍历类获取其所有属性及属性值