c#反射基本用法

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;

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值