日期:2014-05-18 浏览次数:21040 次
protected static void test() { //获取程序集 Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();//Assembly.LoadFrom("test.dll"); //获取模块 Module[] modules = assembly.GetModules(); foreach (Module module in modules) { Console.WriteLine("module name:" + module.Name); } //获取类 Type type = assembly.GetType("Reflect_test.PurchaseOrderHeadManageModel", true, true); //命名空间名称 + 类名 //创建类的实例 object obj = Activator.CreateInstance(type, true); //获取私有字段 FieldInfo[] myfields = type.GetFields(BindingFlags.NonPublic | BindingFlags.IgnoreCase | BindingFlags.Instance); for (int i = 0; i < myfields.Length; i++) { Console.WriteLine("字段名:{0},类型:{1}", myfields[i].Name, myfields[i].FieldType); } //获取公共属性 PropertyInfo[] Propertys = type.GetProperties(); for (int i = 0; i < Propertys.Length; i++) { // Propertys[i].SetValue(Propertys[i], i, null); //设置值 // Propertys[i].GetValue(Propertys[i],null); //获取值 Console.WriteLine("属性名:{0},类型:{1}",Propertys[i].Name,Propertys[i].PropertyType); } //构造函数集合 ConstructorInfo[] myconstructors = type.GetConstructors(); foreach (ConstructorInfo csinfo in myconstructors) { Console.WriteLine("ConstructorInfo:{0}",csinfo.Name); foreach (ParameterInfo pinfo in csinfo.GetParameters())//构造函数参数列表 { Console.WriteLine("Parameter:{0},{1}", pinfo.Name,pinfo.ParameterType); } } //公共方法,包括属性 MethodInfo[] methods = type.GetMethods(); foreach (MethodInfo method in methods) { //IsSpecialName:是否是属性 if (!method.IsSpecialName) { // Console.WriteLine("类型:" + method.Attributes); Console.WriteLine("method name:" + method.Name); } } //调用静态方法 int result = (int)type.InvokeMember("StaticPlus", BindingFlags.InvokeMethod, null, null, new object[] {2,3 }); Console.WriteLine("调用静态方法-结果是:{0}",result); //调用非静态方法 result = (int)type.InvokeMember("Plus", BindingFlags.InvokeMethod, null, obj, new object[] { 3, 4 }); Console.WriteLine("调用非静态方法-结果是:{0}",result); EventInfo[] Myevents=type.GetEvents(); foreach (EventInfo einfo in Myevents) { Console.WriteLine("事件:{0}", einfo.Name); } }