开发者

.NET Reflection: how do I loop through an object that is an array type?

I've got a method that returns an array, the type of which I have stored in a Type object further up. The code I have for this is thus:

Type StoryType = Type.GetType("my.ns.Story");
Type StoryTypeArray = Type.GetType("my.ns.Story[]");

object stories = SomeMethodInfo.Invoke(BigFatObject,some_params);

In this example, I know stories is of type StoryTypeArray, and what I really want to do is something like:

foreach (Story instance in stories) { ... }

However, I can't figure out how to tur开发者_如何学Gon the object stories into something I can loop through and pull data out of.

Any ideas?


It's not clear from your question if the Story type is actually known to you at compile time. If it is, the solution is trivial; just cast stores to Story[] and iterate over it as usual:

foreach(Story instance in (Story[])stories) { ... }

This also means that StoryType can be written as typeof(Story) and StoryTypeArray can be written as typeof(StoryTypeArray[]) instead of using the less-safe Type.GetType that you're using.

If the type is not actually known to you at compile time, then you won't be able to write foreach(Story instance..., since that won't be a valid type. If you just want to iterate over the array, then you can do this:

foreach(object item in (Array)stories) { ... }


If for some reasons you've got to do this through reflection, here is the solution:

a.GetType().GetMethod("Get").Invoke(a, new object[]{0})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜