动态加载和卸载 DLL

Posted _ali

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了动态加载和卸载 DLL相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary1
{
    public class Class1
    {
        public static void DoStuff(string msg)
        {
            Console.WriteLine("Class1.DoStuff: " + msg);
            
        }
    }
}

上面是调用的DLL源码

调用主程序源码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            AppDomain ad = AppDomain.CreateDomain("Test");

            // Loader lives in another AppDomain
            Loader loader = (Loader)ad.CreateInstanceAndUnwrap(
                typeof(Loader).Assembly.FullName,
                typeof(Loader).FullName);

            loader.LoadAssembly(@"..\..\..\ClassLibrary1\bin\Debug\ClassLibrary1.dll");
            loader.ExecuteStaticMethod(
                "ClassLibrary1.Class1",
                "DoStuff",
                DateTime.Now.ToShortDateString());
            AppDomain.Unload(ad);
            Console.ReadLine();
            
        }
        class Loader : MarshalByRefObject 
        {
            private Assembly _assembly;

            public override object InitializeLifetimeService() {
                return null;
            }

            public void LoadAssembly( string path ) {
                _assembly = Assembly.Load( AssemblyName.GetAssemblyName( path ) );
            }

            public object ExecuteStaticMethod( string typeName, string methodName, params object[] parameters ) {
                Type type = _assembly.GetType( typeName );
                // TODO: this won‘t work if there are overloads available
                MethodInfo method = type.GetMethod(
                    methodName,
                    BindingFlags.Static | BindingFlags.Public );
                return method.Invoke( null, parameters );
            }
        }
    }
}

 

以上是关于动态加载和卸载 DLL的主要内容,如果未能解决你的问题,请参考以下文章

C#中动态加载和卸载DLL

AppDomain 详解二-C#中动态加载和卸载DLL

C#.Net 如何动态加载与卸载程序集(.dll或者.exe)

AppDomain 卷影副本 - 加载/卸载动态加载的 Dll

vb.net编程,如何使用 appdomain 实现某进程DLL动态加载和卸载?

使用AppDomain进行动态加载和卸载dll