开发者

How to create new COM object with parameters?

I have COM object with few constructors, I'm trying to create new instance and passing parameters to the constructor using powershell 2.0. But I'm getting this error: Parameter set cannot be resolved using the specified named parameters.

This is the code:

$paramsInfo = New-Object -ComObject 'MyObject.ObjectA' 
$开发者_如何学JAVAcomObj = New-Object -ComObject 'MyObject.ObjectB'  -ArgumentList  $paramsInfo

This code doesn't work!!! Any help?


COM has no concept of a constructor. It follows a hyper-pure interfaced-based programming style, implementation is always hidden and you only ever work with interfaces. Interfaces are very easy to make portable across language runtimes, implementation never is. Lots of languages that implement COM have no notion of a constructor, it is an OOP concept.

COM objects are created with the CoCreateInstance() API function, the standard factory method for COM objects. It has no way to pass any kind of arguments to the real class factory that it could use to pass arguments to the constructor. The real factory is the IClassFactory interface implementation, hyper-pure style.

While many languages support making their classes visible to COM clients (like .NET's [ComVisible] attribute), only their parameter-less constructor will ever be called. Necessarily so.

If you need a factory method that takes arguments then just write your own. Implement your own factory interface. No restrictions on the arguments you can pass to its Create() method, how you pass them to the constructor is an invisible implementation detail :)


For a COM object, try using the -Property hashtable instead of -ArgumentList.

$comObj = new-object -com 'MyObject.ObjectB' -Property @{propToSet=$paramsInfo}

Ref: http://technet.microsoft.com/en-us/library/dd315334.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜