我正在尝试确定运行时类型是否是某种集合类型。我在下面的内容有效,但我必须像我所做的那样命名我认为是数组中的集合类型的类型,这似乎很奇怪。
在下面的代码中,之所以使用通用逻辑,是因为在我的应用中,我希望所有集合都是通用的。
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));
}
我如何重构此代码以使其更智能或更简单?
最佳答案
实际上所有这些类型都继承了 IEnumerable
.您只能检查它:
bool IsEnumerableType(Type type)
{
return (type.GetInterface(nameof(IEnumerable)) != null);
}
或者如果您确实需要检查 ICollection:
bool IsCollectionType(Type type)
{
return (type.GetInterface(nameof(ICollection)) != null);
}
查看“语法”部分:
如果您需要排除字符串(本质上是一个 IEnumerable
bool IsEnumerableType(Type type)
{
return (type.Name != nameof(String)
&& type.GetInterface(nameof(IEnumerable)) != null);
}
关于c# - 如何判断一个类型是不是集合类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10864611/