什么是COM Interop的通用集合的替代品?

Mik*_*nry 10 .net generics collections com-interop asp-classic

我试图从.NET程序集返回一系列部门,以便通过COM Interop使用ASP.使用.NET我会返回一个通用集合,例如List<Department>,但似乎泛型不适用于COM Interop.那么,我的选择是什么?

我想迭代列表并能够通过索引访问项目.我应该继承List<Department>,实施IList,IList<Department>或另一个接口,或者是有没有更好的办法?理想情况下,我不希望为我需要的每种类型的列表实现自定义集合.此外,List[index]甚至可以使用COM Interop?

谢谢,迈克

示例.NET组件(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
    }
}
Run Code Online (Sandbox Code Playgroud)

示例ASP代码:

<%
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 %>
Run Code Online (Sandbox Code Playgroud)

相关问题:

Mik*_*nry 11

经过一些研究和反复试验后,我想我找到了一个解决方案System.Collections.ArrayList.但是,这不适用于通过索引获取值.要做到这一点,我创建了一个新的类ComArrayList,从继承ArrayList,并增加了新的方法GetByIndexSetByIndex.

COM Interop兼容集合:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

更新的.NET组件MyLibrary.GetDepartments:

public ComArrayList GetDepartments() {
    // return a list of Departments from the database
}
Run Code Online (Sandbox Code Playgroud)

更新的ASP:

<h1>The third department</h1>
<%= departments.GetByIndex(2).Name %>
Run Code Online (Sandbox Code Playgroud)


Chr*_*ter 5

由于您只是在ASP中使用数据,我建议您返回Department[].这应该直接映射到COM中的SAFEARRAY.它也支持枚举和索引访问.

public Department[] GetDepartments() {
    var departments = new List<Department>();
    // populate list from database
    return departments.ToArray();
}
Run Code Online (Sandbox Code Playgroud)