Asp呼叫c#編製的com元件的實例
1 新建類別庫MyTestDLL
2 右鍵點選項目MyTestDLL-》屬性-》產生-》勾選為COM互通註冊
3 開啟AssemblyInfo.cs 檔案修改[assembly: ComVisible(true)]
4 開啟Visual Sutdio 2008 的命令提示列工具輸入guidgen.exe 選擇DEFINE_GUID 點選New GUID
5代碼
1.每個類別名對應一個介面名,介面名是類別名稱前加上一個大寫的I
2.介面中宣告的方法要使用屬性[DispId(n)]
3、類別必須有一個無參構造函數
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace MyTestDll
{
// 這裡Guid為第4步產生的。
[Guid(FFA4B191-FB5B-4dd5-B7B1-B2F32BF6F1FF)]
public interface IMyTestDll
{
[DispId(0)]
string GetAbout();
}
public class Test1:IMyTestDll
{
PRivate string summary;
public Test1()
{
summary = 這是我的第一個測試;
}
public string GetAbout()
{
return summary;
}
}
}
6 生成項目
asp測試程式碼
<%
Dim o
Set o = Server.CreateObject(MyTestDll.Test1)
Response.Write o.GetAbout()
Set o=Nothing
%>
提示:如果要在其他的電腦使用我們用C#開發的這個COM元件還需要是用regasm來註冊
方法為:
先把bin/Debug目錄的檔案拷貝到目標電腦上,然後開啟指令提示列工具輸入:
regasm 你拷貝到的目錄/檔名.dll /tlb f:/dll/檔名.tlb /codebase
運作既可在該電腦上使用