ReadOnlyCollection中的对象[]
我有一个通过反射调用最终得到的对象:
object readOnlyCollectionObject = propertyInfo.GetValue(someEntity, null);
我知道这个对象是一个通用的 ReadOnlycollection。 它可以是 ReadOnlyCollection
、ReadOnlyCollection
等。出于论证目的,我们只说它是 ReadOnlyCollection
>。
尽管 Dog 派生自对象,但我知道 ReadOnlyCollection
并不是派生自 ReadOnlyCollection
我想知道如何以对象引用数组的形式从 ReadOnlyCollection 中获取所有元素,而不必知道 ReadOnlyCollection
的特定类型 (T)。
I have an object that I ended up with via a reflection call:
object readOnlyCollectionObject = propertyInfo.GetValue(someEntity, null);
I know this object is a generic ReadOnlycollection. It could be a ReadOnlyCollection<Cat>
, ReadOnlyCollection<Dog>
, etc. For argument sake, lets just say it is a ReadOnlyCollection<T>
.
Even though a Dog derives from an object, I know that a ReadOnlyCollection<Dog>
does not derive from a ReadOnlyCollection<object>
. So even if I use reflection to call the CopyTo method I still need to know the specific type of ReadOnlyCollection, which is what I want to avoid.
I want to know how to get all the elements out of the ReadOnlyCollection as an array of object references without having to know the specific type (T) of the ReadOnlyCollection<T>
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
许多其他答案都提到了 Cast() 和 ToArray,这些都存在类型问题。 正如您所说,您不会知道您的财产将实现哪个专门的 IEnumerable。 但是,您可以确定它们都将实现非通用 ICollection 接口。
或
编辑:忘记更新从 IEnumerable 到 ICollection 的转换
Many other answers mention Cast() and ToArray, those all have a problem with the type. As you say, you won't know which specialized IEnumerable your property will implement. However, you can be sure that they will all implement the non-generic ICollection interface.
or
Edit: Forgot to update the cast from IEnumerable to ICollection
那么,您可以在 上使用 Cast 扩展方法readonly 集合,然后将其转换为对象数组,但是,基于 C# 数组是协变这一事实,您可以简单地执行以下操作:
(编辑)
正如 Pop Catalin 提到的,只有当
T
是引用类型时才有效。 否则请使用 Cast 方法。(edit2)
您对问题的更新改变了很多事情......我认为您想要做的事情是不可能的。 您希望在编译时转换为仅在运行时可用的显式类型。 在这种情况下,访问集合的唯一方法是使用反射。
Well, you can use the Cast extension method on the readonly collection and then convert it to an array of objects but, based on the fact that in c# arrays are covariant, you can simply do:
(edit)
As Pop Catalin mentioned, the only works if
T
is a reference type. Use the Cast method otherwise.(edit2)
Your update to the question changes things quite a bit ... I think that what you're trying to do is not possible. You want to cast to a explicit Type at compile time that is only available at runtime. In this case, the only way you have to access the collection is with reflection.
将集合转换为对象列表,然后调用 ToArray():
由于扩展方法的原因,仅适用于 C# 3.5。
Cast your collection to a list of objects, then call ToArray():
Works only in C# 3.5 because of the extension methods.
您想要该系列的深度克隆吗? 如果您想深度克隆,请尝试以下代码进行内存深度克隆:
Do you want a deep clone of the collection? If you want to deep clone try this code below for memory deep cloning: