如果对象是泛型列表



有什么方法可以确定对象是否是泛型列表吗?我不知道列表的类型,我只知道它是一个列表。我该如何确定?

这将返回"True"

List<int> myList = new List<int>();
Console.Write(myList.GetType().IsGenericType && myList is IEnumerable);

你想知道它是否真的是一个"列表"。。。还是你同意它是IEnumerable和Generic?

以下方法将返回泛型集合类型的项类型。如果类型未实现ICollection<>则返回null。

static Type GetGenericCollectionItemType(Type type)
{
    if (type.IsGenericType)
    {
        var args = type.GetGenericArguments();
        if (args.Length == 1 &&
            typeof(ICollection<>).MakeGenericType(args).IsAssignableFrom(type))
        {
            return args[0];
        }
    }
    return null;
}

编辑:以上解决方案假设指定的类型有自己的泛型参数。这将不适用于实现ICollection<>的类型带有硬编码的通用参数,例如:

class PersonCollection : List<Person> {}

这里有一个新的实现来处理这个案例。

static Type GetGenericCollectionItemType(Type type)
{
    return type.GetInterfaces()
        .Where(face => face.IsGenericType &&
                       face.GetGenericTypeDefinition() == typeof(ICollection<>))
        .Select(face => face.GetGenericArguments()[0])
        .FirstOrDefault();
}

接受的答案不能保证IList<>的类型。检查这个版本,它对我有效:

private static bool IsList(object value)
{
    var type = value.GetType();
    var targetType = typeof (IList<>);
    return type.GetInterfaces().Any(i => i.IsGenericType 
                                      && i.GetGenericTypeDefinition() == targetType);
}

尝试:

if(yourList.GetType().IsGenericType)
{
  var genericTypeParams = yourList.GetType().GetGenericArguments;
  //do something interesting with the types..
}

这个问题不明确。

答案取决于你所说的一般列表是什么意思。

  • 列表<SomeType>

  • 从List<SomeType>

  • 实现IList<SomeType>(在这种情况下,数组可以被视为泛型列表,例如int[]实现IList<int>)?

  • 一个通用的实现IEnumerable的类(这是公认答案中提出的测试)?但这也会将以下相当病态的类别视为一个通用列表:

public class MyClass<T> : IEnumerable
{
    IEnumerator IEnumerable.GetEnumerator()
    {
        return null;
    }
}

最佳解决方案(例如,是否使用GetType、IsAssignableFrom等)将取决于您的意思。

System.Object类中有一个GetType()函数。你试过了吗?

最新更新