【问题标题】:Why I can convert to this one type and not the other?为什么我可以转换为这种类型而不是另一种?
【发布时间】:2017-06-22 21:55:34
【问题描述】:

错误 45 'System.Collections.Generic.List(Of String)' 不能 转换为“System.Collections.Generic.List(Of Object)”。考虑 使用'System.Collections.Generic.IEnumerable(对象)' 反而。 H:\business\shared\Dropbox\vb.net\proxyhandler.vb 198 19 nicehash2

这是我得到的错误。替换

System.Collections.Generic.List(Of Object)

System.Collections.Generic.IEnumerable(Of Object)

解决问题。

我知道第二种类型是接口。我还是一头雾水。

但是为什么呢?

【问题讨论】:

    标签: vb.net generics


    【解决方案1】:

    由于列表是可变的(您可以添加项目),您不能将 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!
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 2021-01-03
      • 2012-03-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多