如何确定类型是否是一种集合?
我试图确定运行时类型是否是某种集合类型。 我在下面的工作,但似乎很奇怪,我必须将我认为的数据类型命名为数组,就像我所做的那样。
在下面的代码中,通用逻辑的原因是因为,在我的应用程序中,我希望所有集合都是通用的。
bool IsCollectionType(Type type) { if (!type.GetGenericArguments().Any()) return false; Type genericTypeDefinition = type.GetGenericTypeDefinition(); var collectionTypes = new[] { typeof(IEnumerable), typeof(ICollection), typeof(IList), typeof(List) }; return collectionTypes.Any(x => x.IsAssignableFrom(genericTypeDefinition)); }
我如何重构此代码以使其更智能或更简单?
实际上所有这些类型都inheritance了IEnumerable
。 你只能检查它:
bool IsEnumerableType(Type type) { return (type.GetInterface(nameof(IEnumerable)) != null); }
或者如果你真的需要检查ICollection:
bool IsCollectionType(Type type) { return (type.GetInterface(nameof(ICollection)) != null); }
看看“语法”部分:
-
List
-
IList
-
ICollection
您可以使用此帮助程序方法检查类型是否实现了开放的通用接口。 在您的情况下,您可以使用DoesTypeSupportInterface(type, typeof(Collection<>))
public static bool DoesTypeSupportInterface(Type type,Type inter) { if(inter.IsAssignableFrom(type)) return true; if(type.GetInterfaces().Any(i=>i. IsGenericType && i.GetGenericTypeDefinition()==inter)) return true; return false; }
或者您可以简单地检查非通用的IEnumerable
。 所有集合接口都从它inheritance。 但我不会调用任何实现IEnumerable
集合的类型。
所有这些都inheritance了IEnumerable(),这意味着检查它应该足够了:
我知道这个post已经老了但是这是一个现代的例子,截至2015年7月20日,根据微软的关键字。
if(collection is ICollection) return true;
您可以使用linq,搜索类似的接口名称
yourobject.GetType().GetInterfaces().Where(s => s.Name == "IEnumerable")
如果这个值是IEnumerable
一个实例。