Vb.NET - 自定义模板类的GetEnumerator

时间:2013-07-29 13:30:20

标签: vb.net ienumerable

我有像这样的通用类构建

Public Class TabellaCustom(Of myType, TValue) Implements IEnumerable(Of TValue)
Private mKey As myType
Private mContenuto As TValue

...

Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of TValue) Implements System.Collections.Generic.IEnumerable(Of TValue).GetEnumerator
        Return DirectCast(mContenuto, IEnumerator(Of TValue))
End Function

当我做这样的事情时

dim Color as new ColorsEnumerable
Dim test(0) As StampeCommonFunctions.TabellaCustom(Of Color, String)
test(0) = New StampeCommonFunctions.TabellaCustom(Of Color, String)(Color.Red, "Red")

test.GetEnumerator()

我收到了一个错误:

 Unable to cast object of type 'System.String' to type 'System.Collections.Generic.IEnumerator`1[System.String]'.

如何解决此错误?我必须在类中指定对象的类型吗?

1 个答案:

答案 0 :(得分:1)

好吧,mContenuto是一个字符串,您尝试将其转换为IEnumerator(Of String),但string类未实现IEnumerator(Of String)

这就是异常告诉你的。

您的课程似乎只包含两个值(mKeymContenuto),您为什么要实施IEnumerable<T>?似乎没有必要这样......


你可以像这样实现GetEnumerator

Public Function GetEnumerator() As System.Collections.Generic.IEnumerator(Of TValue) Implements System.Collections.Generic.IEnumerable(Of TValue).GetEnumerator
    Return {Me.mContenuto}.AsEnumerable().GetEnumerator()
End Function

Private Function GetEnumerator1() As System.Collections.IEnumerator Implements System.Collections.IEnumerable.GetEnumerator
    Return GetEnumerator()
End Function

这可以通过从mContenuto创建单个元素数组并返回其Enumerator来实现。

相关问题