开发者

What's the quickest way to test if an object is IEnumerable?

开发者 https://www.devze.com 2023-03-21 16:25 出处:网络
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

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

0

精彩评论

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