首页 > 代码库 > 动态加载和卸载 DLL
动态加载和卸载 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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。