What's the quickest way to test if an object is IEnumerable?
Is开发者_StackOverflow中文版 there a quick way to find out if an object
variable's contents supports IEnumerable? Specifically I'm using XPathEvaluate()
from System.Xml.XPath, which can return "An object that can contain a bool, a double, a string, or an IEnumerable."
So after executing:
XDocument content = XDocument.Load("foo.xml");
object action = content.XPathEvaluate("/bar/baz/@quux");
// Do I now call action.ToString(), or foreach(var foo in action)?
I could poke around with action.GetType().GetInterface()
, but I thought I'd ask if there's a quicker/easier way.
You are looking for the is
operator:
if(action is IEnumerable)
or even better, the as
operator.
IEnumerable enumerable = (action as IEnumerable);
if(enumerable != null)
{
foreach(var item in enumerable)
{
...
}
}
Note that string
also implements IEnumerable
, so you might like to extend that check to if(enumerable != null && !(action is string))
Use the is
operator:
if(action is IEnumerable)
This is what it does:
An is expression evaluates to true if the provided expression is non-null, and the provided object can be cast to the provided type without causing an exception to be thrown.
If you just need to test if an object is of a type then use is
. If you need to use that object after use as
so that the runtime must only do the cast once:
IEnumerable e = action as IEnumerable
if(null != e)
{
// Use e.
}
This should work.
action is IEnumerable;
try this one
if(action is IENumerable)
{
//do some stuff
}
hth
精彩评论