【问题标题】:Converting line of code from VB to C#将代码行从 VB 转换为 C#
【发布时间】:2014-10-04 18:54:01
【问题描述】:

我正在尝试将一段代码从 VB 转换为 C#,但遇到了一行代码的问题。

VB 代码:

Dim tsAV As System.Windows.Forms.ToolStrip = 
    CType(objHost.FormMain.Controls("tsMain"), Windows.Forms.ToolStrip)

我在 C# 中的代码:

System.Windows.Forms.ToolStrip tsAV = 
    (System.Windows.Forms.ToolStrip)objHost.FormMain;

我的问题出在 FormMain 方法上。当我使用 VB 代码时,我可以获得 Controls 方法,但在 C# 中我不能。我使用包含两种方式的相同接口 DLL。

我做错了吗? DLL 是否可以包含某些仅在 VB 中有效的内容?

【问题讨论】:

  • 什么是objHost?这个变量的类型是什么?
  • 什么是FormMain - 类或实例?

标签: c# vb.net ctype


【解决方案1】:

您应该可以将其用作您的 C# 代码:

// using System.Windows.Forms;
ToolStrip tsAV = (ToolStrip)objHost.FormMain().Controls["tsMain"];
                                            ^^^^^^^^^^^^^^^^^^^

在您的示例中,您尝试将 Form 转换为 ToolStrip,但这是行不通的。

【讨论】:

  • 我的问题是 Visual Studio 在写出来时对我大喊“FormMain 是一种方法,不能在这种情况下使用”,就像在 C# 中一样。在 VB 中它工作得很好。
  • VB 在方法调用中不使用括号更加宽容。 C# 不是,当它告诉您应该只需要在方法调用中添加括号时。我已更新我的帖子以反映这一点。
  • 哇,我可以发誓我试过了哈哈,但它奏效了!非常感谢您的帮助!还在学习哈哈:)
【解决方案2】:

如果您尝试在 c# 表单中检索 ToolStrip,您可以使用以下代码。这假定 ToolStrip 名称为“tsAV”,并且您正在从 FormMain (可能是主窗体的类名)中的方法执行此代码。

using System.Windows.Forms;
...
ToolStrip tsAV = (ToolStrip)Controls["tsMain"];

在表单之外,您可以使用以下代码找到 ToolStrip:

using System.Windows.Forms;
...
FormMain form = new FormMain();
ToolStrip tsAV = (ToolStrip)form.Controls["tsMain"];

更新:假设objHost 是某种控制器,FormMain 是返回表单的实例而不是类名的字段或属性名称,您可以使用以下:

using System.Windows.Forms;
...
ToolStrip tsAV = (ToolStrip)objHost.FormMain.Controls["tsMain"];

【讨论】:

  • 感谢您的帮助! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-29
  • 1970-01-01
  • 2018-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多