简体   繁体   English

如何在C#中创建对象?

[英]How to CreateObject in C#?

I want to translate the following VB6 code into C# 我想将以下VB6代码转换为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: 我使用TlbImp.exe为COM类创建包装器,然后尝试执行以下操作:

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 但是没有构造函数接受host参数

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. sHost变量包含一台计算机的名称,该计算机提供进程外COM服务器。 The equivalent functionality is provided by Type.GetTypeFromProgId(), using the overload that allows specifying the server name: Type.GetTypeFromProgId()通过使用允许指定服务器名称的重载来提供等效的功能:

  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. 我将其命名为“ obj”,请避免给变量指定与接口类型相同的名称。 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. 庞大的工作量仍可能出错,使COM服务器在客户端和服务器计算机上正确注册并正确设置DCOM安全对于使此代码正常工作至关重要。 Don't try this until you are sure that the original code works properly. 在确定原始代码正常工作之前,请不要尝试此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM