c# - 如何判断一个类型是不是集合类型?

标签 c# collections types refactoring

我正在尝试确定运行时类型是否是某种集合类型。我在下面的内容有效,但我必须像我所做的那样命名我认为是数组中的集合类型的类型,这似乎很奇怪。

在下面的代码中,之所以使用通用逻辑,是因为在我的应用中,我希望所有集合都是通用的。

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/

相关文章:

database - Liquibase 数据类型映射文档

javascript - 为什么 JavaScript 按位或行为异常?

python - dtype : integer, 但 loc 返回 float

c# - 应用打开时的调用方法

c# - 在 null IEnumerables 上为 Count() 返回零

java - 如何在scala中将java列表转换为数组?

java - TreeMap 的 entrySet() 是否返回一个 TreeSet

c# - 相当于c#中的AbstractTableModel

c# - 根据地区更新报表查看器货币

c# - 如何从 Azure Key Vault 获取 VaultProperties.NetworkAcls 属性