【问题标题】:How do you pass a VB collection to a function from c# code?如何将 VB 集合从 c# 代码传递给函数?
【发布时间】:2018-05-11 20:44:03
【问题描述】:

我有一个 dll,它有一个函数,需要几个 Microsoft.VisualBasic.Collection 类型的变量。但我尝试在 C# 中将它们作为 An Arraylist 和 A List 传递,但无济于事。

  Severity  Code    Description Project File    Line    Suppression State
  Error CS1502  The best overloaded method match for 
 'Object.RptOptimizer.BuildReport(string, string, System.Guid, 
 Microsoft.VisualBasic.Collection, Microsoft.VisualBasic.Collection, string, 
 string, System.DateTime, System.DateTime, string, string, string, string, 
 string, int, bool, int, int, bool)' has some invalid arguments EPWeb4   
 C:\inetpub\wwwroot\EPWeb4\Forms\RptParamsOptimizer.aspx.cs 271 Active

 Severity   Code    Description Project File    Line    Suppression State
 Error  CS0012  The type 'Collection' is defined in an assembly that is not 
 referenced. You must add a reference to assembly 'Microsoft.VisualBasic, 
 Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.    

【问题讨论】:

  • 也许显示您尝试过的代码以及您正在调用的函数的方法签名?
  • 也许你也可以给我们看一些代码?这将有助于了解更多
  • 根据docs,它位于Microsoft.VisualBasic.dll,所以请参阅How to add reference to Microsoft.VisualBasic.dll?。事实上,这可能是重复的。或者只是在 c# 中将其声明为IList。然后只需在 c# 中将其声明为Microsoft.VisualBasic.Collection。或者将其声明为IList,因为Collection 实现了这个接口。
  • 顺便说一句,您应该更喜欢使用类型化的泛型集合。见Benefits of GenericsWhen would you not use Generic Collections?

标签: c# asp.net


【解决方案1】:

Microsoft.VisualBasic.Collection 实现了 ICollectionIList,就像许多标准 BCL 集合一样。

static void Main(string[] args)
{
    Microsoft.VisualBasic.Collection c = new Microsoft.VisualBasic.Collection();

    c.Add(new { Id = 1, Name = "John"});
    c.Add(new { Id = 2, Name = "Mary" });

    DoSomething(c);

    Console.ReadLine();
}

public static void DoSomething(ICollection collection)
{
    foreach (dynamic v in collection)
    {
        Console.WriteLine($"{v.Id} - {v.Name}");
    }
}

根据上述错误,您还缺少 C# 项目的引用页面中对 Microsoft Visual Basic 程序集的程序集引用。

右键单击项目 > 添加 > 参考 ... > 程序集选项卡 > 向下滚动到 Microsoft.VisualBasic 并勾选以包含它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-15
    • 1970-01-01
    • 2021-07-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多