---
title: "c#编写com组件以及在silverlight中调用"
author: "piperzero"
date: "2013-02-21T11:51:00Z"
tags: []
slug: "c-com-silverlight"
draft: false
lastmod: "2013-02-21T19:55:33Z"
id: 1811688
url: "https://piperzero.iteye.com/blog/1811688"
---

1.创建windows类库项目

![](http://img.my.csdn.net/uploads/201302/21/1361415005_8641.png)

2.AssemblyInfo.cs设置ComVisible(false) --&gt; ComVisible(true)

![](http://img.my.csdn.net/uploads/201302/21/1361415179_3811.png)

3.项目属性中，Build选项中勾选

![](http://img.my.csdn.net/uploads/201302/21/1361415166_7282.png)

4.往下，Signing选项中注册程序集，勾选Sign the assembly, 选择New...

![](http://img.my.csdn.net/uploads/201302/21/1361415423_5311.png)

5.输入名字，随便自己取个名字，去掉Project my key file a password

![](http://img.my.csdn.net/uploads/201302/21/1361415477_1421.png)

6.修改成自己的类名

![](http://img.my.csdn.net/uploads/201302/21/1361415303_4444.png)

7.编写代码

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Runtime.InteropServices;

namespace RXCOM  
{  
\[ComVisible(true)]  
\[Guid("39116335-A4BB-4A2B-A461-90779B386CE5")]  
public interface IRXCOM

{  
void Initialize();  
void Dispose();  
int Add(int x, int y);  
}  
\[ComVisible(true)]  
\[Guid("C944C444-6231-4515-9422-48B4B7277462")]  
\[ProgId("RXCOM.IMCOM")]  
public classIMCOM :IRXCOM  
{  
public void Initialize()  
{  
//nothing todo  
}  
public void Dispose()  
{  
//nothing todo  
}  
public int Add(int x, int y)  
{  
return x + y;  
}  
}

}

8、GUID属性里面的那个字符串，在“Tools”菜单下面，“Create GUID”  
选择 Registry Format，Copy,Exit

![](http://img.my.csdn.net/uploads/201302/21/1361415705_2223.png)

9.编译dll，使用命令C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\RegAsm.exe RXCOM.dll注册com。

以上com组件已经编写完成。下面介绍如何在silverlight中调用该组件

\-----------------------------------------------------------------------------------------------------------------------------

1.silverlight项目中必须选择OOB模式，并且修改安全级别，勾选Enable running application out of the browser

![](http://img.my.csdn.net/uploads/201302/21/1361418782_3465.png)

2.打开Out-of-Browser Settings,勾选如下

![](http://img.my.csdn.net/uploads/201302/21/1361418903_1450.png)

3.编写silverlight调用代码,执行接口中的方法

dynamic IMDCOM = AutomationFactory.CreateObject("RXCOM.IMCOM");

dynamic result = IMDCOM.Add(100,200);