(C#基础)反射理解
这个知识点很基础。
代码
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace dazilianxi { public class book:IComparable { private int price; private string title; public book() { } public book(int price ,string title) { this.price = price; this.title = title; } public int Price { get { return this.price; } } public string Title { get { return this.title; } } #region IComparable 成员 public int CompareTo(object obj) { book mbook = (book)obj; return this.Price.CompareTo(mbook.Price); } public string DisplayName(string name) { return string.Format("学生姓名:{0}", name); } #endregion } }
运行的main中代码:
/* Type type = Type.GetType("dazilianxi.book"); Console.WriteLine(type.Name); Console.WriteLine(type.FullName); Console.WriteLine(type.Namespace); //获取属性 PropertyInfo[] info = type.GetProperties(); foreach( PropertyInfo item in info ) { Console.WriteLine(item.Name); } Console.WriteLine("下面试方法"); //获取方法 MethodInfo[] meth = type.GetMethods(); foreach(MethodInfo me in meth) { Console.WriteLine(me.ReturnType.Name); Console.WriteLine(me.Name); } */ book lob = new book( 100,"好书刊"); //获取运行时的程序集 Assembly asm = Assembly.GetExecutingAssembly(); //获取运行时的Type类型 Type type = asm.GetType("dazilianxi.book"); //获取运行时的对象实例 object stu = Activator.CreateInstance(type); //获取运行时指定方法 MethodInfo method = type.GetMethod("DisplayName"); object[] parameters = new object[1];//定义参数数组 parameters[0] = "88lll";//参数赋值 // parameters[1] = "hello"; //触发运行时的方法 string result = (string)method.Invoke(stu, parameters);//得到实例参数结果值 Console.WriteLine(result);
参考:http://www.cnblogs.com/darrenji/p/3817999.html