如何将VB6中的对象集合传递给.NET?

时间:2013-03-27 00:03:26

标签: c# .net vb6 interop com-interop

我需要将一串键/值对的字符串从VB6传递给.NET。在VB6代码中,它们存在于本机集合中。但我不确定在我的.NET项目中我可以引用什么能够在我的一个方法中接受Collection类型的参数。

我尝试添加对Visual Basic for Applications的引用但返回“无法添加对'Visual Basic For Applications'的引用。”

我是否采取了错误的方式?

3 个答案:

答案 0 :(得分:3)

你可以在c#中使用这样的东西:

[Guid("fb5e929a-2f8b-481e-9516-97edf5099df4")]
[ComVisible(true)]
public interface myInterface{
public void addObject(string key, string value);
}

在你的课堂上,你可以拥有这个:

private collection
public addObject(string key, string value)
{
collection.Add(key, value);
}

这应该允许您在vb6中调用addObject并传递数据。然后.net会将它添加到一个集合中,所以不是将整个集合从vb6传递到.net,而是逐个传递它们。

您可以阅读有关GUID here.

的更多信息

有关COM的更多信息以及vb6 and c# here.

之间的代码示例

答案 1 :(得分:2)

我没有使用COM,而是将我的数据序列化为JSON并将其作为纯文本发送到Interop鸿沟上,这样做更为简单。我一开始就拒绝它,但它现在是我的首选解决方案。如果“适当的”解决方案令人沮丧,请尝试一下。

答案 2 :(得分:1)

尝试通过在Visual Basic 6.0中创建HashTable来将其传递给.NET

Set dictionary = Server.CreateObject("System.Collections.HashTable")
With dictionary
    For i = 1 To 100
        .Add Chr(i), "some text value"
    Next
End With

然后在C#或VB.NET COM公开的课程中

public string LoadHashTable(Object tDict)
{
   return String.Format("Type : \"{0}\", Count : {1}", ((Hashtable)tDict).GetType().ToString(), ((Hashtable)tDict).Count);
}

COM暴露类的示例位于Stack Overflow问题 Building a COM interop library for ASP Classic using 4.0 framework and Visual Studio 2010

请记住在x86和x64中注册它:

%windir%\Microsoft.NET\Framework\v4.0.30319\regasm MyThing.dll /tlb:MyThing.tlb /codebase MyThing

%windir%\Microsoft.NET\Framework64\v4.0.30319\regasm MyThing.dll /tlb:MyThing.tlb /codebase MyThing