代码之家  ›  专栏  ›  技术社区  ›  Paul Sasik

VB.NET为每一步进入循环体的一个IEnumerable集合!怎么用?为什么?

  •  -1
  • Paul Sasik  · 技术社区  · 14 年前

    我有一个从IEnumrable继承的类,它的Count属性报告0(零)个元素,但是For Each循环进入循环体,并尝试在应该继续的地方使用变量。我的代码:

        On Error Resume Next
        Dim d As Foo
        For Each d In fooCollection
            ' use d and throws an exception
        Next d
    

    更奇怪的是,每次访问d时,我都会在输出窗口中抛出一个异常:

    '系统.NullReferenceException'

    是“下一步继续出错”导致了这种奇怪吗?

    发现怪异之处:

    Foo中的GetEnumerator方法实际上没有返回任何东西!它的身体是空的。再加上下一个错误恢复之前的循环造成了巨大的破坏!哇,太难看了。谢谢你们的线索!

    4 回复  |  直到 9 年前
        1
  •  1
  •   JonH    14 年前

    在下一步继续时消除错误。你能贴出Foo的样子吗?

        2
  •  2
  •   Hans Passant    14 年前

    看吧,错误的罪恶在下一步继续。当fooCollection引用为Nothing时,它会恢复到循环中。

        3
  •  2
  •   Dan Puzey    14 年前

    IEnumerable和Count没有关系。当你做这件事的时候 For Each 你基本上是这样做的:

    Dim en as IEnumerator = fooCollection.GetEnumerator()
    While en.MoveNext()
       d = en.Current()
       ' your code here...
    Wend
    

        4
  •  0
  •   Eric    9 年前

    下面是一个清除图表所有系列点的util方法,无需删除系列本身:

    ' clear all serial of a chart
    Public Sub clearChart(ByVal chart As Chart)
        Dim sc As SeriesCollection = chart.Series
        Dim etor As IEnumerator = sc.GetEnumerator()
        Dim serial As Series
    
        While etor.MoveNext()
            serial = etor.Current()
            serial.Points.Clear()
        End While
    End Sub