【问题标题】:Add items from ObjectCollection to an IList(Of SomeType)将 ObjectCollection 中的项目添加到 IList(Of SomeType)
【发布时间】:2011-05-09 00:49:24
【问题描述】:

如何将 ObjectCollection 项添加到 IList(Of SomeType)? 我试过了:

For Each obj As SomeType In listBox.Items 'ObjectCollection
    MyObject.ItProperty.Add(obj) 'IList
Next

没有成功。 谢谢。

【问题讨论】:

  • 我认为您遗漏了一些文字。它以“我尝试过:”结尾。
  • 我已经改变了。对不起,谢谢。

标签: .net vb.net collections object ilist


【解决方案1】:

你能补充一些关于失败的地方和地方的细节吗?您的代码应该可以工作。

如果您在“For Each obj”行收到异常 "Unable to cast object of type 'XXX' to type 'SomeType'.",则 listBox.Items 集合中至少有一个不属于“SomeType”类型的项目。

【讨论】:

    【解决方案2】:

    如果可能,非泛型 IList 接口将是最简单的方法:

    IList list = (IList)MyObject.ItProperty;
    list.Add(obj);
    

    否则,您将不得不:

    • 找到合适的T(使用反射)
    • IList<T> 解析Add 方法(使用反射)
    • 调用Add 方法(使用反射)

    这种反射,尤其是泛型,并不好。

    作为替代方案 - 如果您有 4.0,您可以尝试使用 dynamic,但请注意,这只会看到公共 API。不过值得一试(仅当IList 失败时):

    dynamic list = MyObject.ItProperty;
    list.Add(obj); // let's hope Add isn't an explicit interface implementation
    

    【讨论】:

      猜你喜欢
      • 2012-10-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-03
      • 2017-01-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多