C#反射加载程序集并使用

具体实现参考:

C# 动态加载DLL通过反射调用参数、方法、窗体_c#反射加载dll并传入参数-CSDN博客

C#进阶学习--反射(Reflection) - 知乎

走进C#反射机制 - 知乎

1.使用过程
cs 复制代码
//创建数据集
Assembly outerAsm = Assembly.LoadFile("D:/your.dll");

//获取调用类型声明,要把命名空间带上
Type typeClass = outerAsm.GetType("namespace1.classNameA");

//获取静态方法声明
MethodInfo methodStatic = typeClass1.GetMethod("staticFunc");

//调用无参静态方法
object methoVal = methodStatic.Invoke(null, null);

//创建实体,有参构造
object obj1 = Activator.CreateInstance(typeClass, new object[]{ para1,para2,...,paraN });

//创建实体,无参构造
object obj2 = Activator.CreateInstance(typeClass, null });

//获取非静态方法声明
MethodInfo methodGetInit = typeProduct.GetMethod("nonStaticFunc");

//调用无参非静态方法
methodGetInit.Invoke(obj1 , null);

//获取名为Property1的访问器
PropertyInfo propertyInfo = typeProduct.GetProperty("Property1");声明

//获取product中名为Property1的访问器的值
object obj1 = propertyInfo.GetValue(product);
2.loadfrom、loadfile

参考:Assembly.LoadFile 方法 (System.Reflection) | Microsoft Learn

1)loadfrom

加载程序集的时候会连带性的加载,会连带把该文件所依赖的dll也加载

2)loadfile

仅加载一个文件,不会连带把该文件所依赖的dll也加载

3.其他补充

**1)**当前,在一个AppDomain中只能加载dll,不能卸载,因此在一个AppDomain中不能有同名的dll程序集

**2)**一个线程属于一个AppDoMain

参考:C# AppDomain 详解

3)AssemblyResolve

AssemblyResolve一般配合load方法使用,在load方法找不到程序集的时候,会调用AssemblyResolve解决冲突

cs 复制代码
AppDomain.CurrentDomain.AssemblyResolve -= OnAssemblyResolve;
List<string> Searchs = new List<string>() {"path1","path2" };
Assembly OnAssemblyResolve(object sender, ResolveEventArgs args)
{
    var assemblyName = new AssemblyName(args.Name);

    foreach(var item in Searchs)
    {
        var file = string.Format("{0}.dll", System.IO.Path.Combine(item, assemblyName.Name));
        if (File.Exists(file))
        {
            return Assembly.LoadFile(file);
        }
    }

    return args.RequestingAssembly;
}

4)常见的冲突

要动态加载的dll跟输出目录中的dll冲突了,尤其是调用loadfrom的时候,其所依赖的dll一般会从输出目录中获取,但是输出目录中的dll并不是你想要的依赖版本,这时候就会冲突

相关推荐
小羊没烦恼!3 天前
初探性能优化——2个月到4小时的性能提升
java·开发语言·windows·算法·c#
神仙别闹3 天前
基于C#+MySQL实现(WinForm)个人聊天室软件
c#
伞伞悦读3 天前
【第38期】Python 模块与包详解:import、from、模块搜索路径、包结构和 __init__
开发语言·python
C语言小火车3 天前
C/C++ 为什么需要编译器?
开发语言·c++
霍霍的袁3 天前
【C++】map 和 set 的使用 | 从用法到底层
开发语言·c++·学习·visual studio
kybs19913 天前
全球灾害数据分析可视化 毕业设计-附源码66794
vue.js·spring boot·mysql·安全·django·c#·asp.net
孙启超3 天前
【AI开发之Rust】第 11 课:智能指针与内部可变性
开发语言·后端·rust
此生决int3 天前
深入理解C++系列(20)——C++11(下)
开发语言·c++
CoderYanger3 天前
A.每日一题:835. 图像重叠
java·开发语言·程序人生·leetcode·面试·职场和发展·学习方法
伞伞悦读3 天前
【第37期】Python JSON 与配置详解:序列化、反序列化、嵌套结构和配置文件
开发语言·python·json