2

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

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

没有成功。谢谢你。

4

2 回答 2

1

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

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

否则,您将不得不:

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

这种反思,尤其是对泛型的反思,并不好。

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

dynamic list = MyObject.ItProperty;
list.Add(obj); // let's hope Add isn't an explicit interface implementation
于 2010-11-12T12:54:44.947 回答
0

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

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

于 2011-02-08T19:48:38.740 回答