开发者

foreach on unknown type

I need to be able to loop around an unknown type for example

  foreach (var test in viewData["开发者_Python百科foobar"])
  {
  }

Any suggestions


You have to at least cast viewData["foobar"] to IEnumerable to have objects in your test variable.

The cast may fail, so you'll first have to check whether viewData["foobar"] actually implements IEnumerable with is or as operator:

if(viewData["foobar"] is IEnumerable)
    foreach(var test in (IEnumerable)viewData["foobar"])

Note that this is using System.Collections.IEnumerable, not System.Collections.Generic.IEnumerable<>.


If viewData["foobar"] is of the type object, then you can't iterate over it. The only way to iterate with a foreach loop is on IEnumerator derived types.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜