Dot-Net

COM 互操作的通用集合的替代方案是什麼?

  • February 20, 2012

我試圖從 .NET 程序集中返回一組部門,以供 ASP 通過 COM 互操作使用。使用 .NET 我只會返回一個泛型集合,例如List<Department>,但泛型似乎不適用於 COM 互操作。那麼,我有哪些選擇?

我想遍歷列表並能夠按索引訪問項目。我應該繼承、List<Department>實現一個或另一個介面,還是有更好的方法?理想情況下,我寧願不必為我需要的每種類型的列表實現自定義集合。此外,甚至可以與 COM Interop 一起使用嗎?IList``IList<Department>``List[index]

謝謝,邁克

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

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

相關問題:

經過更多的研究和反複試驗,我想我找到了使用System.Collections.ArrayList. 但是,這不適用於按索引獲取值。為此,我創建了一個新類ComArrayList,它繼承ArrayList並添加了新方法GetByIndexSetByIndex.

COM 互操作兼容集合:

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

引用自:https://stackoverflow.com/questions/269581