我想将以下VB6代码转换为C#
I want to translate the following VB6 code into C#
If optHost(0).Value Then Set m_oScpiAccess = New IcSCPIActiveX.IcSCPIAccess Else sHost = txtHost.Text Set m_oScpiAccess = CreateObject("Exfo.IcSCPIActiveX.IcSCPIAccess", sHost) End If我使用TlbImp.exe为COM类创建包装,然后尝试:
I used TlbImp.exe to create wrappers for the COM classes, and I tried:
if (string.IsNullOrEmpty(host)) { // this works IcSCPIAccess = new IcSCPIAccess(); } else { // throws MissingMethodException IcSCPIAccess = (IcSCPIAccess)Activator.CreateInstance( typeof(IcSCPIAccessClass), host); }但是没有构造函数接受 host 参数
But there is no constructor which accepts the host parameter
推荐答案这不是构造函数调用。 sHost 变量包含一台计算机的名称,该计算机提供进程外COM服务器。 Type.GetTypeFromProgId()使用允许指定服务器名称的重载来提供等效的功能:
It is not a constructor call. The sHost variable contains the name of a machine, the one that provides the out-of-process COM server. The equivalent functionality is provided by Type.GetTypeFromProgId(), using the overload that allows specifying the server name:
var t = Type.GetTypeFromProgID("Exfo.IcSCPIActiveX.IcSCPIAccess", sHost, true); obj = (IcSCPIAccess)Activator.CreateInstance(t);我将其命名为 obj,请避免为变量指定与接口类型相同的名称。庞大的工作量仍可能出错,使COM服务器在客户端和服务器计算机上正确注册并正确设置DCOM安全对于使此代码正常工作至关重要。在确定原始代码正确运行之前,请不要尝试此操作。
I named it "obj", do avoid giving variables the same name as the interface type. A gazillion things can still go wrong, having the COM server properly registered both on the client and server machine and setting the DCOM security correctly is essential to make this code work. Don't try this until you are sure that the original code works properly.
更多推荐
如何在C#中创建对象?
发布评论