2

我创建了一个 ComVisible 类:

[Guid("73a3f91f-baa9-46ab-94b8-e526c22054a4"), ComVisible(true)]
public interface ITest
{
    void Foo();
}

[Guid("99f72d92-b302-4fde-89bb-2dac899f5a48"), ComVisible(true)]
public class Class1 : ITest
{
    public void Foo() { }
}

并通过注册

regasm ComClassTest.dll /tlb:ComClassTest.tlb

进入注册表。当我尝试在我的 Silverlight 4 浏览器外调用它时,提升的信任应用程序如下所示:

var foo = AutomationFactory.CreateObject("ComClassTest.Class1");

我收到异常“{System.Exception:无法为指定的 ProgID 创建对象实例。”

但是,如果我复制 ComClassTest,我可以在没有异常的情况下调用 AutomationFactory.CreateObject("Word.Application") 并在普通 C# 控制台应用程序中调用 Activator.CreateInstance(Type.GetTypeFromProgID("ComClassTest.Class1")) .dll 进入 bin 目录。

我忘记了什么?

4

1 回答 1

0

First thing to do is test that you can create the object from somewhere else such as VBScript. Create a .vbs file with the content:-

o = CreateObject("ComClassTest.Class1")

If that doesn't generate an error then there is something specifically that SL OOB is upset with otherwise your problem isn't really related to Silverlight at all.

Consider making the following changes to your COM code.

  • Its often easier to specify ComVisible(true) at the assembly level. You can do that from the application tab of the project properties on the Assembly Information dialog. You can also get Visual Studio to register the assembly with COM and build time using the option found on the build tab of the project properties.

  • Its a good idea to be specific about the ComInterfaceType you want to expose.

  • Things get really messy if you expose the class interface directly generally you only want the interface you have defined to be used and that this be the default interface for the class. In addition it probably better to stick to COM naming conventions for the default interface of a class.

  • Finally (and possibly crucially in your case) its a good idea to be explicit about the ProgId to use for the class.

Applying the above and we get:-

[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[Guid("73a3f91f-baa9-46ab-94b8-e526c22054a4")]
public interface _Class1
{
    void Foo();
}

[ClassInterface(ClassInterfaceType.None)] 
[Guid("99f72d92-b302-4fde-89bb-2dac899f5a48")]
[ProgId("ComClassTest.Class1")]
public class Class1 : _Class1
{
    public void Foo() { }
}
于 2010-12-18T18:43:30.613 回答