System.Reflection.Assembly類有兩個靜態方法:Assembly.Load(string assemblyname)和Assembly.LoadFrom(string filename) 。通常用這兩個方法把程序集加載到應用程序域中。 如果你希望加載的程序集超出了CLR的預定探查范圍,你可以用 Assembly.LoadFrom直接從一個文件位置加載程序集。Assembly.LoadFrom()和Assembly.LoadFile(),兩者的主要區別有兩點:
一:Assembly.LoadFile()只載入指定的dll文件,而不會自動加載相關的dll文件。如果下文例子使用Assembly.LoadFile()加載SayHello.dll,那么程序就只會加載SayHello.dll而不會去加載SayHello.dll引用的BaseClass.dll文件。
二:用Assembly.LoadFrom()載入一個Assembly時,會先檢查前面是否已經載入過相同名字的Assembly;而Assembly.LoadFile()則不會做類似的檢查。

using System; using System.Collections.Generic; using System.Text; namespace BaseDLL { public class BaseClass { public static void SetTitle() { Console.WriteLine("BaseClass中的方法"); } } }

using System; using System.Collections.Generic; using System.Text; namespace SayHello { public class HelloClass { public string SayHello(int helloTimes, string name) { BaseDLL.BaseClass.SetTitle(); string reslut = string.Empty; for (int i = 0; i < helloTimes; i++) { reslut += "Hello," + name + "\n"; } return reslut; } } }

using System; using System.Collections.Generic; using System.Text; using System.Reflection; using System.IO; namespace Reflection { class Program { static void Main(string[] args) { handle01: Console.WriteLine("請輸入加載的DLL的位置:"); string filePath = Console.ReadLine(); if (File.Exists(filePath)) { System.Reflection.Assembly ass = Assembly.LoadFrom(filePath); Type[] collection = ass.GetTypes(); foreach (var item in collection) { string className = item.FullName.ToString(); Console.WriteLine(className); } } else { Console.WriteLine("文件不存在,請重新輸入文檔地址"); goto handle01; } Console.ReadKey(); } } }