0

我有一个像这样的通用类构建

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]'.

我该如何解决这个错误?我必须在类中指定对象的类型?

4

1 回答 1

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.

于 2013-07-29T13:35:11.370 回答