开发者

foreach on unknown type

开发者 https://www.devze.com 2022-12-16 22:41 出处:网络
I need to be able to loop around an unknown type for example foreach (var test in viewData[\"开发者_Python百科foobar\"])

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

精彩评论

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