如何确定对象是否类型为IEnumerable< T>?
代码:
namespace NS { class Program { static IEnumerable< int> GetInts(){ yield return 1; } static void Main(){ var i = GetInts(); var type = i.GetType(); Console.WriteLine(type.ToString()); } } }输出:
NS.1.Program +< GetInts> d__0b $ b
如果我改变GetInts返回IList,一切正常输出是:
System.Collections.Generic.List`1 [System.Int32]:
命名空间NS { class Program { static IEnumerable< int& GetInts(){ yield return 1; } static void Main(){ var i = GetInts(); var type = i.GetType(); Console.WriteLine(type.Equals(typeof(IEnumerable< int>)))); } } }解决方案>
如果您的意思是集合,则为:
var asEnumerable = i as IEnumerable< int> ;; if(asEnumerable!= null){...}假设(从示例中)您拥有类型:
永远不是of类型 IEnumerable< int> - 但它可能会实现我希望:
if(typeof(IEnumerable< int>)。IsAssignableFrom(type)){...}如果你不知道上面的 T ( int ),那么检查所有实现的接口: p>
static类型GetEnumerableType(类型类型){ foreach(type.GetInterfaces()中的类型intType){ if(intType.IsGenericType & intType.GetGenericTypeDefinition()== typeof(IEnumerable<>)){ return intType.GetGenericArguments()[0]; } } return null; }并致电:
类型t = GetEnumerableType(type);如果为null,则不是 IEnumerable< T& code>任何 T - 否则请检查 t 。
How to determine if object is of type IEnumerable <T>?
Code:
namespace NS { class Program { static IEnumerable<int> GetInts() { yield return 1; } static void Main() { var i = GetInts(); var type = i.GetType(); Console.WriteLine(type.ToString()); } } }Output:
NS.1.Program+<GetInts>d__0If I change GetInts to return IList, everything is OK the output is:
System.Collections.Generic.List`1[System.Int32]And this returns false:
namespace NS { class Program { static IEnumerable<int> GetInts() { yield return 1; } static void Main() { var i = GetInts(); var type = i.GetType(); Console.WriteLine(type.Equals(typeof(IEnumerable<int>))); } } }解决方案
If you mean the collection, then just as:
var asEnumerable = i as IEnumerable<int>; if(asEnumerable != null) { ... }However, I'm assuming (from the example) that you have a Type:
The object will never be "of" type IEnumerable<int> - but it might implement it; I would expect that:
if(typeof(IEnumerable<int>).IsAssignableFrom(type)) {...}would do. If you don't know the T (int in the above), then check all the implemented interfaces:
static Type GetEnumerableType(Type type) { foreach (Type intType in type.GetInterfaces()) { if (intType.IsGenericType && intType.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { return intType.GetGenericArguments()[0]; } } return null; }and call:
Type t = GetEnumerableType(type);if this is null, it isn't IEnumerable<T> for any T - otherwise check t.
更多推荐
确定集合是否类型为IEnumerable< T>
发布评论