C# -- 使用反射(Reflect)获取dll文件中的类型并调用方法

使用反射(Reflect)获取dll文件中的类型并调用方法

需引用:System.Reflection;

1. 使用反射(Reflect)获取dll文件中的类型并调用方法(入门案例)

 1         static void Main(string[] args)
 2         {
 3             //dll文件路径
 4             string path = @"D:\VS2015Project\001\Computer\bin\Debug\computer.dll";
 5 
 6             //加载dll文件
 7             Assembly asm = Assembly.LoadFile(path);
 8 
 9             //获取类
10             Type type = asm.GetType("Computer.Computer");
11 
12             //创建该类型的实例
13             object obj = Activator.CreateInstance(type);
14 
15             //获取该类的方法
16             MethodInfo mf = type.GetMethod("ShowDrives");
17 
18             //调用方法
19             mf.Invoke(obj, null);
20 
21             Console.ReadKey();
22         }

 

2. 生成类库(computer.dll)的computer.cs文件代码

 1 using System;
 2 using System.Collections.Generic;
 3 using System.IO;
 4 using System.Linq;
 5 using System.Text;
 6 
 7 
 8 namespace Computer
 9 {
10     public class Computer
11     {
12         private DriveInfo[] drives;
13         public Computer()
14         {
15             this.drives = DriveInfo.GetDrives();
16         }
17         public void ShowDrives()
18         {
19             Console.WriteLine("该电脑的磁盘驱动器有:\r\n");
20             foreach (var item in drives)
21             {
22                 Console.WriteLine(item);
23             }
24         }
25     }
26 }


3. 反射调用结果:

 

posted on 2018-10-18 08:52  在代码的世界里游走  阅读(4344)  评论(0编辑  收藏  举报