2013-07-29 52 views
0

我有一個泛型類建立這樣Vb.NET - 自定義模板類的GetEnumerator

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

那麼,mContenuto是一個字符串,並且您試圖將其轉換爲IEnumerator(Of String),但string類未實現IEnumerator(Of String)

這就是例外告訴你的。

您的班級似乎只是持有兩個值(mKey,mContenuto),您爲什麼要執行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

+0

這僅僅是一個例子;我需要這種類型的泛型類在所有程序中使用它,而不用使兩個字段生成N個不同的類;爲了在同一班級我需要一個TabellaCustom(字符串,整數)和另一部分 TabellaCustom(字符,字符串) 我需要實現Ienumerable 因爲我需要獲取此類內Combobox綁定DisplayMemberPath屬性類屬性Contenuto – AlexF

+0

@Alex因此,您想要將此類的單個實例綁定到ComboBox,以便在ComboBox中只顯示一個值?如果不是,你不應該實現'IEnumerable',而只需將你的類實例放在一個列表中,並將該列表綁定到ComboBox。 – sloth

+0

我試過不實現IEnumerable,但當我把TabellaCustom(字符串,字符串)(例如)在Combobox.ItemsSource列表中它說我需要實現IEnumerable 是的,我需要顯示一個值(通常是可以像描述一樣使用的mContenuto值)。 我正在考慮做一個TabellaCustom(Of myType,string),也許這種方式不夠靈活,但可用 – AlexF