在 .Net COM Interop 中理解 IEnumerable

7

为什么我可以使用VBScript的for each语句遍历System.Collections.ArrayList对象,但无法遍历Systems.Collections.SortedList对象?

考虑以下内容:

set aList = Server.CreateObject("System.Collections.ArrayList")
aList.Add "a"
aList.Add "b"
aList.Add "c"
for each item in aList
    ' do something
next

set sList = Server.CreateObject("System.Collections.SortedList")
sList.Add "a", 1
sList.Add "b", 2
sList.Add "c", 3
for each item in sList
    ' do something
next

这条线

for each item in sList

崩溃并显示:

对象不支持此属性或方法*。

通过此属性,我认为它指的是_NewEnum属性。但为什么ArrayList会公开_NewEnum属性,而SortedList不会呢?这两个类都实现了IEnumberable接口,从反汇编mscorelib.dll中可以看出,该接口负责实现_NewEnum属性(dispId为-4)。

如果有人能解释这些相似类之间的不同COM互操作行为,我会非常感激。

我知道我可以使用SortedList公开的其他属性来迭代集合。 我只是想问为什么在互操作版本的SortedList中没有实现IEnumrable,而在互操作版本的ArrayList中已经实现了。

1个回答

3
尽管SortedList实现了IEnumerable接口,但它有一个重载的GetEnumerator()方法返回IDictionaryEnumerator。你需要显式地将其转换为IEnumerable才能使用返回IEnumerator的重载方法,这可能是你遇到问题的地方。
默认的枚举器与ArrayList的行为不同 - 它会为每个项返回一个DictionaryEntry而不是您可能期望的字符串。
我猜想你可能想使用Values属性,如果你按数字排序,你想要反过来使用Add方法参数。
sList.Add 1, "a"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接