Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
235 views
in Technique[技术] by (71.8m points)

.net - What are alternatives to generic collections for COM Interop?

I am attempting to return a collection of departments from a .NET assembly to be consumed by ASP via COM Interop. Using .NET I would just return a generic collection, e.g. List<Department>, but it seems that generics don't work well with COM Interop. So, what are my options?

I would like to both iterate over the list and be able to access an item by index. Should I inherit from List<Department>, implement an IList, IList<Department> or another interface, or is there a better way? Ideally I would prefer not to have to implement a custom collection for every type of list I need. Also, will List[index] even work with COM Interop?

Thanks, Mike

Example .NET components (C#):

public class Department {
    public string Code { get; private set; }
    public string Name { get; private set; }
    // ...
}

public class MyLibrary {
    public List<Department> GetDepartments() {
        // return a list of Departments from the database
    }
}

Example ASP code:

<%
Function PrintDepartments(departments)
    Dim department
    For Each department In departments
        Response.Write(department.Code & ": " & department.Name & "<br />")
    Next
End Function

Dim myLibrary, departments
Set myLibrary = Server.CreateObject("MyAssembly.MyLibrary")
Set departments = myLibrary.GetDepartments()
%>
<h1>Departments</h1>
<% Call PrintDepartments(departments) %>
<h1>The third department</h1>
<%= departments(2).Name %>

Related questions:

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

After some more research and trial-and-error, I think I found a solution by using System.Collections.ArrayList. However, this does not work with getting a value by index. To do so, I created a new class ComArrayList that inherits from ArrayList and adds new methods GetByIndex and SetByIndex.

COM Interop compatible collection:

public class ComArrayList : System.Collections.ArrayList {
    public virtual object GetByIndex(int index) {
        return base[index];
    }

    public virtual void SetByIndex(int index, object value) {
        base[index] = value;
    }
}

Updated .NET component MyLibrary.GetDepartments:

public ComArrayList GetDepartments() {
    // return a list of Departments from the database
}

Updated ASP:

<h1>The third department</h1>
<%= departments.GetByIndex(2).Name %>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...