假设在C盘根目录下有个Dog的Dll程序集文件,该程序集文件中包含类Dog 该类中有个狗叫几声的方法,如何通过反射来加载这个C:\Dog.dll,并且调用Dog类里面的Sound方法呢:

public class Dog

    public void Sound(int count)

    { Console.WriteLine("叫了{0}声",count); }

}

具体如下:

首先反射主要用到了System.Reflection命名空间,所以程序中一定要引用这个命名空间。

using System.Reflection;
写个测试方法如下:

public void Test()

{

  string assemblyFilePath= @"C:\Dog.dll";

  Assembly ass= Assembly.LoadFile(assemblyFilePath);

  Type t = ass.GetType("Dog",false,false);

  MethodInfo  info = t.GetMethod("Sound");

 object instance = Activator.CreateInstance(t);

 info.Invoke(instance,new object[]{2});//狗叫了两声

}

相关文章:

  • 2021-07-12
  • 2022-12-23
  • 2021-10-23
  • 2021-12-08
  • 2021-09-16
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-09-28
  • 2022-01-17
  • 2021-09-02
  • 2022-03-05
  • 2021-09-23
相关资源
相似解决方案