1、打开想要调用的程序集(把想要调用的类的绝对路径填入Assembly类中的LoadFile方法)
//AppDomain.CurrentDomain.BaseDirectory可以获得当前生成的程序集中的绝对路径
string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"库.dll");
Assembly ass = Assembly.LoadFile(path);
2、使用GetTypes可以获得打开程序集中的所有类型
Type[] types=ass.GetTypes();
#region 获得想获取程序集中类和命名空间
foreach (Type t in types)
{
Console.WriteLine(t.FullName);
Console.WriteLine(t.Name);
Console.WriteLine(t.Namespace);
}
#endregion
3、如果调用的程序集中的构造函数为无参构造函数
//括号里写入要打开的命名空间下的类
object o = ass.CreateInstance("库.Class1");
4、如果调用的程序集中的构造函数为有参构造函数
Type ty = ass.GetType("库.Class1");
object o2 = Activator.CreateInstance(ty, "文豪");
5、获得程序集中的属性
PropertyInfo[] pros = o.GetType().GetProperties();
foreach (PropertyInfo i in pros)
{
Console.WriteLine(i.Name);
}
6、获得程序集中的方法
MethodInfo[] pros1 = o.GetType().GetMethods();
foreach (MethodInfo i in pros1)
{
Console.WriteLine(i.Name);
}
7、执行程序集中的方法
MethodInfo fun = o.GetType().GetMethod("Fun");
fun.Invoke(o, null);//有参数写参数,无参数写null
8、反射四个常用函数
bool IsAssignableFrom(Type c) :判断当前类型变量是否可以接受c类型的赋值
bool b = typeof(Person).IsAssignableFrom(typeof(Student));
bool IsInstanceOfType(object o):判断对象o是否是当前类的实例(当前类可以是o的类,父类,接口)
Student s = new Student();
bool b = typeof(Student).IsInstanceOfType(s);
bool c = s.GetType().IsInstanceOfType(s);
bool IsSubclassOf(Type c):判断当前类是否是类c的子类(不包含接口)
bool b = typeof(Student).IsSubclassOf(typeof(Person));
IsAbstract(Type c):判断是不是抽象类或者接口
bool b = typeof(Person).IsAbstract;