How to check if a variable is an IEnumerable of some sort

后端 未结 9 914
一生所求
一生所求 2021-02-01 12:47

basically I\'m building a very generic T4 template and one of the things I need it to do is say print variable.ToString(). However, I want it to evaluate lists and

9条回答
  •  别跟我提以往
    2021-02-01 13:37

    If you want to test for the non-generic IEnumerable then you'll need to include a using System.Collections directive at the top of your source file.

    If you want to test for an IEnumerable of some kind then you'll need something like this instead:

    if (variable != null)
    {
        if (variable.GetType().GetInterfaces().Any(
                i => i.IsGenericType &&
                i.GetGenericTypeDefinition() == typeof(IEnumerable<>)))
        {
            // foreach...
        }
    }
    

提交回复
热议问题