从FieldInfo.GetValue返回的对象不能转换为Array(Object returned from FieldInfo.GetValue cannot be cast to Array)

编程入门 行业动态 更新时间:2024-10-28 12:16:28
从FieldInfo.GetValue返回的对象不能转换为Array(Object returned from FieldInfo.GetValue cannot be cast to Array)

我正在使用PCL(Profile7),并且我遇到了fieldInfo.GetValue(myItem)返回的对象无法转换为数组的问题。

在使用As时,我在直接转换中获得了转换异常(显然)为null

我如何将这个对象转换为集合?

注意:我不知道该类型是什么,因为我无法访问它。 这是我正在消费的图书馆的内部

I'm working in a PCL (Profile7), and I've got an issue where the object returned from fieldInfo.GetValue(myItem) cannot be cast to an array.

I get a cast exception on a direct cast and (obviously) null when using As

how do I cast this object to a collection?

note: I have no idea what the type is as I don't have access to it. It's internal to the library I'm consuming

最满意答案

检查dynamicProperties对象的类型,它在您显示的调试器屏幕截图中不可见。 很可能它是某种List<> 。

只有当它是一个引用类型数组(如string[]或object[] ,您才会尝试成功,如果类型是结构体,它将会失败,如此问题所示: object to string array

在任何情况下, IReadOnlyCollection<T> , IReadOnlyList<T>和IEnumerable<T>接口都是协变的,您可以尝试转换为IEnumerable<object> ,或者如果您需要更多信息,例如计数或索引器访问,其他接口。

Check the type of the dynamicProperties object, it's not visible in the debugger screenshot that you showed. Most likely it's a List<> of some sort.

The cast you attempt only succeeds if it's an array of reference types (e.g. string[] or object[], it will fail if the type is a struct, as illustrated in this question: object to string array

In any case, the IReadOnlyCollection<T>, IReadOnlyList<T> and IEnumerable<T> interfaces are covariant, you could try casting to IEnumerable<object>, or if you need more information such as count or indexer access, try one of the other interfaces.

更多推荐

本文发布于:2023-04-28 09:44:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1331390.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:转换为   对象   GetValue   FieldInfo   cast

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!