如何确定类型是否是一种集合?

Byr*_*ahl 37 c# collections refactoring types

我试图确定运行时类型是否是某种集合类型.我在下面的工作,但似乎很奇怪,我必须像我所做的那样命名我认为是数组中的集合类型的类型.

在下面的代码中,通用逻辑的原因是因为,在我的应用程序中,我希望所有集合都是通用的.

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));
}
Run Code Online (Sandbox Code Playgroud)

我如何重构此代码以使其更智能或更简单?

Rub*_*ben 67

真的所有这些类型都继承了IEnumerable.你只能检查它:

bool IsEnumerableType(Type type)
{
    return (type.GetInterface(nameof(IEnumerable)) != null);
}
Run Code Online (Sandbox Code Playgroud)

或者如果你真的需要检查ICollection:

bool IsCollectionType(Type type)
{
    return (type.GetInterface(nameof(ICollection)) != null);
}
Run Code Online (Sandbox Code Playgroud)

看看"语法"部分:

  • 检查`IEnumerable`有一个错误地将`string`解释为集合的问题.这在大多数时候都是不可取的. (15认同)
  • 根本不适合我.`ICollection <CPerson>`在`type.GetInterface("ICollection")`和`type.GetInterface("System.Collections.Generic.ICollection")上返回`null`` (2认同)