如何确定是否一种类型是一个类型的集合? [英] How to determine if a type is a type of collection?

查看:217
本文介绍了如何确定是否一种类型是一个类型的集合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,以确定是否运行时类型是某种集合类型。我下面的作品,但它似乎很奇怪,我要的名字,我认为是在一个数组像我这样做集合类型的类型。

I am trying to determine if a runtime type is some sort of collection type. What I have below works, but it seems strange that I have to name the types that I believe to be collection types in an array like I have done.

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

In the code below, the reason for the generic logic is because, in my app, I expect all collections to be generic.

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));
}



我将如何重构这个代码更聪明或者更简单呢?

How would I refactor this code to be smarter or simpler?

推荐答案

真的所有这些类型的继承的 的IEnumerable 。您只能检查它:

Really all of these types inherit IEnumerable. You can check only for it:

bool IsEnumerableType(Type type)
{
    return (type.GetInterface("IEnumerable") != null);
}



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

or if you really need to check for ICollection:

bool IsCollectionType(Type type)
{
    return (type.GetInterface("ICollection") != null);
}



看语法部分:

Look at "Syntax" part:

的IList

的ICollection

这篇关于如何确定是否一种类型是一个类型的集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆