【问题标题】: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