C# 建立 COM+ 組件
- 建立類別庫專案
ComInterop。
- 新增介面
ComInteropInterface 與實作類別 ComInterop (繼承 ServicedComponent)。
完整 C# 代碼
using System;
using System.Runtime.InteropServices;
using System.EnterpriseServices;
namespace ComInteropDemo
{
[Guid("7103C10A-2072-49fc-AD61-475BEE1C5FBB")]
public interface ComInteropInterface
{
[DispId(1)] int Add(int a, int b);
[DispId(2)] int Minus(int a, int b);
}
[Guid("87796E96-EC28-4570-90C3-A395F4F4A7D6")]
[ClassInterface(ClassInterfaceType.None)]
public class ComInterop : ServicedComponent, ComInteropInterface
{
public ComInterop() { }
public int Add(int a, int b) { return a + b; }
public int Minus(int a, int b) { return a - b; }
}
}
關鍵屬性
[Guid]:介面與類別的固定身分 ID。
[DispId]:COM 虛函數表索引,必須顯式指定。
[ClassInterface(ClassInterfaceType.None)]:不自動產生類別介面,僅公開明確定義的介面。
- 繼承
ServicedComponent:支援 COM+ 服務 (交易、物件池等)。
- 專案需:強命名金鑰、
ComVisible(true)、啟用「註冊 COM 互通」。
產生類型庫供 C++ 使用
REGASM ComInteropDemo.dll /tlb ComInteropDemo.tlb
REGASM /u ComInteropDemo.dll (重新建置前解除註冊)