C#动态加载dll创建对象,并调用方法
C#中有一种应用场景,就是根据供应商、服务商、平台等的不同,可以封装不同的类库,但是这些类库都实现同一套接口;
然后在配置文件或者数据库中配置,根据供应商、服务商、平台不同,动态的加载对应的dll,然后创建对象,调用方法;提高系统的扩展性。
示例代码:
// See https://aka.ms/new-console-template for more information
using System.Reflection;
using HotelPlatform;
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
Assembly assembly = Assembly.Load("HotelPlatform");
string className = "HotelPlatform.Order";
Type type = assembly.GetType(className);
//Order o = new Order();
//o.InsertOrder();
if (type != null)
{
object instance = Activator.CreateInstance(type);
string methodName = "InsertOrder";
MethodInfo methodInfo = instance.GetType().GetMethod(methodName);
if (methodInfo != null)
{
methodInfo.Invoke(instance, null);
}
}
}
}