反射

反射

 

//1.动态加载程序集
Assembly ams = Assembly.LoadFile(@"c:\反射复习.dll");

//2.获取类型
//Type[] t = ams.GetTypes();
//获取所有公共类型的
//Type[] t = ams.GetExportedTypes();
//foreach (Type info in t) {
// Console.WriteLine(info);
//}

//3.获取类型中的成员
Type personInfo = ams.GetType("_反射复习.Person");

//获取所有方法
//MethodInfo[] methods = personInfo.GetMethods();
//获取所有属性
//PropertyInfo[] methods = personInfo.GetProperties();
//获取所有字段
//FieldInfo[] methods = personInfo.GetFields();
//获取所有事件
//EventInfo[] methods = personInfo.GetEvents();
//获取所有成员
//MemberInfo[] methods = personInfo.GetMembers();
//for (int i = 0; i < methods.Length; i++) {
// Console.WriteLine(methods[i].Name);
//}

//4、调用SayHi方法
//1.调用无参方法
//MethodInfo methodInfo = personInfo.GetMethod("SayHi");
//MethodInfo methodInfo = personInfo.GetMethod("SayHello", new Type[] { typeof(string) });
//2.调用有参构造方法
//创建对象
//object obj = Activator.CreateInstance(personInfo);
//methodInfo.Invoke(obj, new object[] { "调用有参数的" });
MethodInfo info = personInfo.GetMethod("SayHello", new Type[] { typeof(string) });
info.Invoke(Activator.CreateInstance(personInfo), new object[] { "哈哈" });

Console.ReadKey();

你可能感兴趣的:(反射)