COM Interop 的泛型集合有哪些替代方案? [英] What are alternatives to generic collections for COM Interop?

查看:28
本文介绍了COM Interop 的泛型集合有哪些替代方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从 .NET 程序集中返回一组部门,以便 ASP 通过 COM Interop 使用.使用 .NET 我只会返回一个通用集合,例如List,但泛型似乎不适用于 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?

我想遍历列表并能够通过索引访问项目.我应该从 List 继承,实现 IListIList 或其他接口,还是有更好的方法?理想情况下,我不想为我需要的每种类型的列表实现自定义集合.另外,List[index] 甚至可以与 COM Interop 一起使用吗?

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?

谢谢,迈克

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
    }
}

示例 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 %>

相关问题:

  • 在服务组件上使用通用列表
  • .NET 中的非泛型集合是否已过时?
  • 推荐答案

    经过更多的研究和反复试验,我想我找到了使用 System.Collections.ArrayList 的解决方案.但是,这不适用于按索引获取值.为此,我创建了一个从 ArrayList 继承的新类 ComArrayList,并添加了新方法 GetByIndexSetByIndex.

    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.

    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;
        }
    }
    

    更新了 .NET 组件 MyLibrary.GetDepartments:

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

    更新的 ASP:

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

    这篇关于COM Interop 的泛型集合有哪些替代方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆