如何在C#中创建对象?

编程入门 行业动态 更新时间:2024-10-27 10:21:26
本文介绍了如何在C#中创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我想将以下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#中创建对象?

本文发布于:2023-11-03 06:56:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1554500.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!