本文實例講述了C#編寫COM組件的方法。分享給大家供大家參考,具體如下:
1、新建一個類庫項目
2、將Class1.cs改為我們想要的名字
問是否同時給類改名,確定
3、修改Properties目錄下面的AssemblyInfo.cs
ComVisible屬性設置為True
4、項目菜單->MyLib屬性
找到“生成”選項卡
往下看,找到“為 COM Interop 注冊”勾上
5、繼續往下,找到“簽名”選項卡
勾上“為程序集簽名”
在下面的下拉框里面選擇“ <新建...>”
6、在彈出的對話框里面,輸入MyLib。。或者隨便取個名字
去掉使用密碼保護文件的選項
7、開始編碼,任何一個公開的類,必須有一個 I開通的接口定義
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace MyLib { [ComVisible( true )] [Guid( "2CBD3D76-35F1-4f9d-9C1B-9DBFEE412F76" )] public interface IMyClass { void Initialize(); void Dispose(); int Add( int x, int y); } [ComVisible( true )] [Guid( "EA2F140A-108F-47ae-BBD5-83EEE646CC0D" )] [ProgId( "MyLib.MyClass" )] public class MyClass : IMyClass { public void Initialize() { //nothing todo } public void Dispose() { //nothing todo } public int Add( int x, int y) { return x + y; } } } |
8、GUID屬性里面的那個字符串,在“工具”菜單下面,“創建 GUID”
選擇 Registry Format,然后復制
注意在[Guid("....... 這個里面要去掉GUID前后的花括號
9、編譯它
在命令提示符下面,進入Dll所在的目錄
用 gacutil /i MyLib.dll 將這個DLL加入的全局緩存里
然后用 regasm MyLib.dll 注冊這個dll
10、在javsScript里面試試.
希望本文所述對大家C#程序設計有所幫助。