2017-06-22 92 views
0

錯誤45'System.Collections.Generic.List(Of String)'不能被 轉換爲'System.Collections.Generic.List(Of Object)'。改爲使用'System.Collections.Generic.IEnumerable(Of Object)' 代替 。 H:\ business \ shared \ Dropbox \ vb.net \ proxyhandler.vb 198 19 nicehash2爲什麼我可以轉換爲這種類型而不是其他類型?

這是我得到的錯誤。與

System.Collections.Generic.IEnumerable(Of Object) 

更換

System.Collections.Generic.List(Of Object) 

解決了這個問題。

我知道第二種類型是一個接口。我仍然困惑。

但是爲什麼?

回答

2

由於列表是可變的(您可以f.e.添加項目),您不能將List(Of String)分配給List(Of Object)類型的變量(即使每個字符串都是對象)。

每個List(Of T)也是一個IEnumerable(Of T),但與列表相反,接口不支持修改(而不是將其轉換回實際類型)。這就是爲什麼語言允許使用界面而不是列表。

考慮如果允許列表本身(C# link)上會發生什麼:

Dim giraffes As New List(Of Giraffe) 
giraffes.Add(new Giraffe()) 
Dim animals As List(Of Object) = giraffes ' doesn't compile but what happened otherwise: 
animals.Add(new Lion()) ' Aargh! 
相關問題