65.9K
CodeProject 正在变化。 阅读更多。
Home

在 VB.NET 中调用 C# 程序集函数,这些函数名称仅区分大小写

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.92/5 (17投票s)

2004年8月6日

viewsIcon

64969

在 VB.NET 中调用 C# 程序集函数,这些函数名称仅区分大小写。

问题

我今天遇到了这个问题。我想从我的 VB.NET 代码调用在 C# 中编写的函数,但我发现库的编写者没有遵循 Microsoft 的互操作性指南,而是使用了仅区分大小写的相同名称的两个函数,并且具有相同的签名。我无法访问 C# 代码,因此无能为力,因为 VB.NET 不允许我使用这些函数中的任何一个。它会产生编译时错误

重载解析失败,因为没有可访问的“f<function>”最适合这些参数:<function names>:不是最具体的

解决方案

在这种情况下,我们需要使用反射。至少,我只能找到这个解决方案。

假设我的 C# 程序集代码如下

namespace CompTest
{
  /// <summary>
  /// Summary description for Class1.
  /// </summary>
  public class Class1
  {
    public string cameLate()
    {
      return "He came late";
    }

    public string camelAte()
    {
      return "Camel Ate Him";
    }
  }
}

我们可以在 VB.NET 中按如下方式调用函数 camelAte

Dim CSClass As New CompTest.Class1
Dim ReturnValue As Object
ReturnValue = CSClass.GetType.InvokeMember("camelAte", _
              System.Reflection.BindingFlags.Instance Or _
              BindingFlags.Public Or BindingFlags.InvokeMethod, _
              Nothing, CSClass, Nothing, Nothing, Nothing, Nothing)
TextBox1.Text = ReturnValue

这里使用的 InvokeMember 函数使用指定的绑定约束和匹配的指定参数列表调用指定的成员。您可以在 MSDN 上找到更多信息。

要传递参数,请创建一个 Object 数组。将调用函数所需的参数插入数组中。将数组作为参数传递给 InvokeMethod 函数。

© . All rights reserved.