调用COM类的非默认构造函数 [英] Call non-default constructor of COM class

查看:120
本文介绍了调用COM类的非默认构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个DLL(用C#编写),其中包含带有2个构造函数的类;一个默认的(没有参数)构造函数,另一个是带有3个参数的构造函数.

I have a DLL (written in C#) containing a class with 2 Constructors; a default (no arguments) constructor, and another one with 3 arguments.

在VBscript中,我想调用第二个构造函数,但是 CreateObject 仅接收 classValue 参数,没有可能的 arguments 参数.

In VBscript, I want to call the second constructor, but CreateObject only receives a classValue parameter, no possible arguments parameters.

我猜想 CreateObject 的基础实现使用系统的 CoCreateObject 函数,根据

I guess the underlying implementation of CreateObject uses the system's CoCreateObject function, which according to this answer does not support arguments, but on the other hand there's QTP/UFT's DotNetFactory that is capable of such thing, so there must be a way to do it in pure VBscript.

(如果可能,我想避免使用明显的 init 方法解决方案).

(I want to avoid the obvious init method solution if possible).

关于如何调用我的非默认构造函数的任何想法?

Any ideas for how to call my non-default constructor?

推荐答案

COM不支持将参数传递给构造函数.基础对象工厂方法(IClassFactory :: CreateInstance)不接受参数.

COM does not support passing arguments to a constructor. The underlying object factory method (IClassFactory::CreateInstance) does not accept arguments.

解决方法非常简单,软件工程中的所有问题都可以通过另一层间接解决:)只需创建您自己的工厂方法即可.您可以编写一个采用构造函数所需参数的函数.大概是:

The workaround is pretty simple, all problems in software engineering can be solved by another level of indirection :) Just create your own factory method. You can write one that takes the arguments that the constructor needs. Roughly:

[ComVisible(true)]
public interface IFoo {
   //...
}

class Foo : IFoo {
   public Foo(int a, string b) { ... }
   //...
}

[ComVisible(true)]
public class FooFactory {
    public IFoo CreateInstance(int a, string b) {
        return new Foo(a, b);
    }
}

并且您的VBScript现在可以调用FooFactory的CreateInstance()方法来创建您的类对象.否则,这是COM对象模型中非常常见的模式,Microsoft Office自动化就是一个非常著名的示例.

And your VBScript can now call FooFactory's CreateInstance() method to get your class object created. Otherwise a very common pattern in COM object models, Microsoft Office automation is a very notable example.

这篇关于调用COM类的非默认构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆