创建一个C#类库(在本例中称为DemoComInterface),并确保“使程序集COM可见”未选中。(提醒一下,在以下代码片段中的GUID应替换为您自己的唯一GUID。)
向类库添加一个接口,如下所示:
using System.Runtime.InteropServices;
namespace DemoComInterface
{
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[ComVisible(true)]
[Guid("01B0A84D-CACE-4EF1-9C4B-6995A71F9AB8")]
public interface ISharedInterface
{
[DispId(0x60030040)]
void Question();
}
}
为了演示使用共享接口的C#类,请更新Class1以实现共享接口,并使用以下属性进行装饰:
using System.Runtime.InteropServices;
namespace DemoComInterface
{
[Guid("CC9A9CBC-054A-4C9C-B559-CE39A5EA2742")]
[ProgId("DemoComInterface.Class1")]
[ClassInterface(ClassInterfaceType.None)]
[ComVisible(true)]
public class Class1 : ISharedInterface
{
public void Question()
{
throw new NotImplementedException();
}
}
}
现在,修改你的AssemblyInfo.cs文件中的AssemblyDescription属性为有意义的内容,这样类型库才能在VB6的“引用”浏览器中找到。你可以直接编辑文件或在程序集信息对话框中填写“描述”字段来完成此操作。
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
[assembly: AssemblyTitle("DemoComInterface")]
[assembly: AssemblyDescription("Demo C# exported interfaces")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("DemoComInterface")]
[assembly: AssemblyCopyright("Copyright © 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: ComVisible(false)]
[assembly: Guid("4294f846-dd61-418d-95cc-63400734c876")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
注册此类库,可以通过检查项目的“为COM互操作注册”构建属性或在命令提示符中手动注册它来完成。
查看生成的类型库(位于项目的bin输出文件夹中),您应该会看到类似于以下内容:
[
uuid(4294F846-DD61-418D-95CC-63400734C876),
version(1.0),
helpstring("Demo C# exported interfaces"),
custom(90883F05-3D28-11D2-8F17-00A0C9A6186D, "DemoComInterface, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null")
]
library DemoComInterface
importlib("mscorlib.tlb");
importlib("stdole2.tlb");
interface ISharedInterface;
[
uuid(CC9A9CBC-054A-4C9C-B559-CE39A5EA2742),
version(1.0),
custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "DemoComInterface.Class1")
]
coclass Class1 ;
[
odl,
uuid(01B0A84D-CACE-4EF1-9C4B-6995A71F9AB8),
version(1.0),
dual,
oleautomation,
custom(0F21F359-AB84-41E8-9A78-36D110E6D2F9, "DemoComInterface.ISharedInterface")
]
interface ISharedInterface : IDispatch ;
};
共享接口现在已经在一个COM可见的C#类中实现了。
要在VB6项目中实现共享接口,需要添加对“Demo C# exported interfaces”的引用,并按照以下方式实现:
Option Explicit
Implements ISharedInterface
' Implementation of Question.
Public Sub ISharedInterface_Question()
MsgBox ("Who is number one?")
End Sub