How to CreateObject in C#?

2019-02-16 01:15发布

问题:

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

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);
}

But there is no constructor which accepts the host parameter

回答1:

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);

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.