How to CreateObject in C#?

孤人 提交于 2019-12-03 23:34:05

问题


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.



来源:https://stackoverflow.com/questions/11837245/how-to-createobject-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!