【问题标题】:Assigning a value to IEnumerable type of integer给 IEnumerable 类型的整数赋值
【发布时间】:2013-07-26 19:22:40
【问题描述】:

如何在 VB.Net 中为 IEnumerable 类型的整数数组赋值?

我需要添加:

dim id as integer=obj.id

到数组

dim arr As IEnumerable(Of Integer)

【问题讨论】:

  • 不确定您的意思 - 您是否要求将该值添加到数组中的每个项目?

标签: .net vb.net collections ienumerable


【解决方案1】:

IEnumerable 是一个接口,你不能初始化它。您必须实例化一个具体类型,例如 List,并使用抽象类型(例如 IEnumerable)保留声明。这样做可以保护集合免受写操作,但是当您想要这样做时,您必须将集合转换为允许您添加、删除值的具体类型。示例:

'get value
Dim id as Integer = obj.id

' create your collection and init it with a concrete type
Dim arr As IEnumerable(Of Integer) = new List(Of Integer)

'add in your collection
CType(arr, List(Of Integer).Add(id)

【讨论】:

    【解决方案2】:

    你不能。 IEnumerable(Of T) 不提供任何方法或属性来更改枚举中的任何值。

    考虑一下为什么您认为您的变量 arr 需要是 IEnumerable 类型。

    • 如果您从其他地方获得 IEnumerable 实例,您可以将该枚举的内容添加到 list然后将其他值添加到您的列表中。
    • 或者,即使您出于某种原因想要将arr 声明为IEnumerable,请注意无论如何您都需要实例化一个具体的列表类,您可以在在隐藏所有内容之前向其中添加值在IEnumerable 接口后面供以后只读访问。

    【讨论】:

      【解决方案3】:

      你不能。 IEnumerable 是一个接口,它不代表一个特定的类。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-09
        • 2016-12-19
        • 1970-01-01
        • 1970-01-01
        • 2023-02-07
        • 1970-01-01
        • 2020-12-20
        • 1970-01-01
        相关资源
        最近更新 更多