反射出程序集的属性, 方法及事件.
程序代码:
using System.Windows.Forms; using System.Reflection; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void toolStripTextBox1_KeyPress(object sender, KeyPressEventArgs e) { if (e.KeyChar == (char)Keys.Enter) { //已知程序集的文件名或路径,加载程序集。 Assembly assembly = Assembly.LoadFrom(toolStripTextBox1.Text); TreeNode tn = new TreeNode(); treeView1.Nodes.Clear(); //遍历程序集所有的类 foreach (System.Type t in assembly.GetTypes()) { tn = new TreeNode(t.Name, 1, 1); TreeNode property = new TreeNode("属性", 0, 0); tn.Nodes.Add(property); //遍历每个类的属性 foreach (PropertyInfo p in t.GetProperties()) { TreeNode pn = new TreeNode(p.Name, 0, 0); property.Nodes.Add(pn); } TreeNode method = new TreeNode("方法", 2, 2); tn.Nodes.Add(method); //遍历每个类的方法 foreach (MethodInfo m in t.GetMethods()) { string s = ""; //遍历某个方法的参数 foreach (ParameterInfo par in m.GetParameters()) { s += string.Format("{0} {1},", par.ParameterType.Name, par.Name); } if (s.Length > 0) s = s.Substring(0, s.Length - 1); s = m.ReturnType.Name + " " + m.Name + "(" + s + ")"; TreeNode mn = new TreeNode(s, 2, 2); method.Nodes.Add(mn); } TreeNode even = new TreeNode("事件", 3, 3); tn.Nodes.Add(even); //遍历每个类的事件 foreach (EventInfo ei in t.GetEvents()) { string s = ("event " + ei.EventHandlerType.Name + " " + ei.Name); TreeNode en = new TreeNode(s, 3, 3); even.Nodes.Add(en); } treeView1.Nodes.Add(tn); } } } } }
运行效果:
" border="0" />
源码:
WindowsFormsApplication1.rar
(59.86 KB)