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 object
s 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.
精彩评论