How can I pass a collection of objects from VB6 to .NET?

家住魔仙堡 提交于 2019-12-11 02:04:53

问题


I need to pass a collection of key/value pairs of strings from VB6 to .NET. In VB6 code they exist in a native collection. But I am not sure what I can reference in my .NET project to be able to accept a parameter of type Collection in one of my methods.

I tried adding a reference to Visual Basic for Applications but got back "A reference to 'Visual Basic For Applications' could not be added."

Am I going about it the wrong way?


回答1:


You could use something like this in c#:

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

And in your class, you could have this:

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

This should allow you to call addObject in vb6 and passing your data. Then .net will add it to a collection, so instead of passing your whole collection from vb6 to .net, you pass them one by one.

You can read more about the GUID here.

More info about COM with an exemple of code between vb6 and c# here.




回答2:


Rather than using COM, I have found it far simpler to just serialize my data as JSON and send it over the Interop chasm as plain text. I resisted it at first, but it is now my go-to solution. Give it a try if the "proper" solutions prove frustrating.




回答3:


Try passing it to .NET by making a HashTable in Visual Basic 6.0:

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

Then in a C# or VB.NET COM exposed class

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

An example of a COM exposed class is in Stack Overflow question Building a COM interop library for ASP Classic using 4.0 framework and Visual Studio 2010

Remember to register it in both x86 and 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


来源:https://stackoverflow.com/questions/15649696/how-can-i-pass-a-collection-of-objects-from-vb6-to-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!