我正在尝试创建一个 COM 对象并在 COM+ 下注册它。一切似乎都很顺利,但是当我查看组件服务并深入研究时
Console Root | Component Services | Computers | My Computer | COM+ Applications | TestCom | Components | TestCom.Com.MyCom | Interfaces | _MyCom | Methods
我没有看到列出我的方法。
在我的项目属性中,我已经签署了我的程序集。
AssemblyInfo.cs:
[assembly: ApplicationName("TestCom")]
[assembly: ApplicationAccessControl(false)]
[assembly: ApplicationActivation(ActivationOption.Server)]
[assembly: ComVisible(true)]
MyCom.cs
使用系统; 使用 System.EnterpriseServices;
namespace TestCom.Com
{
[Transaction(TransactionOption.Required)]
public class MyCom : ServicedComponent
{
[AutoComplete]
public int GetIntFromCom()
{
var results = new Random(DateTime.Now.Second).Next();
return results;
}
}
}
我构建 dll 并在 VS2012 命令提示符下运行 regsvcs TestCom.Com.dll。这导致:
Installed Assembly:
Assembly: c:\TestCom.Com.dll Application: TestCom TypeLib: c:\TestCom.Com.tlb
我一定是遗漏了什么,我就是想不出来是什么。
最佳答案
您在这里使用的是默认设置。 [ComVisible] 对象支持的默认接口(interface)是 IDispatch,仅适用于后期绑定(bind)。这是 Microsoft 喜欢的方式,当客户端代码采用不同版本的组件时,痛苦会少得多,这个问题称为 DLL hell 。脚本语言总是使用 IDispatch 并且不需要方法可见。编译型语言通常支持早期绑定(bind),您可以添加类型库,您将获得语法错误检查和自动完成以及大大提高运行时性能。编程时非常方便,但 DLL hell 来袭时风险很大。
如果您想查看这些方法,则必须在您声明的公共(public)接口(interface)上使用 [InterfaceType(ComInterfaceType.InterfaceIsDual)]
属性。它在类型库中公开 IDispatch 和 接口(interface)类型。您将不再拥有自动生成的 _MyCom
界面,您会看到自己的界面。您通常将其称为 IMyCom
。
这需要显式声明接口(interface),以便您可以应用该属性。如果您不以这种方式开始,通常会带来一些不便。您还可以将 [ClassInterface(ClassInterfaceType.AutoDual)]
应用于您公开的公共(public)类。缺点是您还公开了 System.Object 的成员并依赖于 .NET Framework 类型库。这没关系。
关于c# - 为什么我的 COM 对象不显示组件服务中的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20401469/