//Program.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1Text
{
class Program
{
static void Main(string[] args)
{
MyDLL Dll= new MyDLL();
Model.IO.IClass1 obj = Dll.Creat < Model.IO.IClass1>("TestModel.dll", "TestModel", "TestModel.Class1", null);
string str = Test(obj);
Console.Write(str);
Console.ReadLine();
}
public static string Test(Model.IO.IClass1 ClassA)
{
return ClassA.HelloWord();
}
}
}
//TestModel.dll --嵌入的資源
using System;
using System.Collections.Generic;
using System.Text;
namespace TestModel
{
public class Class1 : Model.IO.IClass1
{
public string HelloWord()
{
return "Hellp Word ! /r/n";
}
}
}
//Model.IO 介面
using System;
namespace Model.IO
{
public interface IClass1
{
string HelloWord();
}
}
//MyDLL 類
using System.IO; // 對檔的讀寫需要用到此命名空間
using System.Reflection; // 使用 Assembly 類需用此命名空間
using System.Reflection.Emit; // 使用 ILGenerator 需用此命名空間
public partial class MyDLL
{
//聲明一靜態變數MyAssembly:
// 記錄要導入的程式集
static Assembly MyAssembly;
/// <summary>
/// DLL位元組處理
/// </summary>
/// <param name="Assembly"></param>
/// <returns></returns>
public delegate byte[] LoadDLLHandler(byte[] Assembly);
/// <summary>
/// DLL位元組處理
/// </summary>
public event LoadDLLHandler LoadDLLEventArgs;
//添加LoadDll方法:
private byte[] LoadDll(string lpFileName)
{
Assembly NowAssembly = Assembly.GetEntryAssembly();
Stream fs = null;
try
{// 嘗試讀取資源中的 DLL
fs = NowAssembly.GetManifestResourceStream(NowAssembly.GetName().Name + "." + lpFileName);
}
finally
{// 如果資源沒有所需的 DLL ,就查看硬碟上有沒有,有的話就讀取
if (fs == null && !File.Exists(lpFileName)) throw (new Exception(" 找不到檔 :" + lpFileName));
else if (fs == null && File.Exists(lpFileName))
{
FileStream Fs = new FileStream(lpFileName, FileMode.Open);
fs = (Stream)Fs;
}
}
byte[] buffer = new byte[(int)fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
if (LoadDLLEventArgs != null)
{
return LoadDLLEventArgs(buffer);
}
return buffer; // 以 byte[] 返回讀到的 DLL
}
/// <summary>
/// //添加UnLoadDll方法來卸載DLL:
/// </summary>
public void UnLoadDll()
{// 使 MyAssembly 指空
MyAssembly = null;
}
/// <summary>
/// 從資源創建實例
/// </summary>
/// <param name="lpFileName">資源名稱</param>
/// <param name="Namespace">命名空間</param>
/// <param name="FullClassName">完整類名</param>
/// <param name="args">參數</param>
/// <returns>創建的實例</returns>
public T Creat<T>(string lpFileName, string Namespace, string FullClassName, object[] args)
{
object objType = null;
try
{// 判斷 MyAssembly 是否為空或 MyAssembly 的命名空間不等於要調用方法的命名空間,如果條件為真,就用 Assembly.Load 載入所需 DLL 作為程式集
if (MyAssembly == null || MyAssembly.GetName().Name != Namespace)
MyAssembly = Assembly.Load(LoadDll(lpFileName));
objType = MyAssembly.CreateInstance(FullClassName, true, BindingFlags.Default, null, args, System.Globalization.CultureInfo.CurrentCulture, null);//反射創建
}
catch (System.NullReferenceException e)
{
throw e;
}
return (T)objType;
}
}
文章出處:飛諾網(www.diybl.com):HTTP://www.diybl.com/course/3_program/cshapo/csharpjs/20100714/442698.html
留言列表